我有一个数据帧,由一个具有不断变化的列数的for循环创建.
在另一个函数中,我希望删除最后五列.
具有数据帧长度的变量是"单位",其数字在10和150之间.
我已经尝试使用列的名称,但它不起作用.(一旦我尝试打开"newframe"R工作室崩溃,查看myframe就没问题).
drops <- c("name1","name2","name3","name4","name5")
newframe <- results[,!(names(myframe) %in% drops)]
Run Code Online (Sandbox Code Playgroud)
有没有办法只删除数据帧的最后五列而不依赖于列的名称或数字
我在优化一段R代码时遇到了麻烦.以下示例代码应说明我的优化问题:
一些初始化和函数定义:
a <- c(10,20,30,40,50,60,70,80)
b <- c(“a”,”b”,”c”,”d”,”z”,”g”,”h”,”r”)
c <- c(1,2,3,4,5,6,7,8)
myframe <- data.frame(a,b,c)
values <- vector(length=columns)
solution <- matrix(nrow=nrow(myframe),ncol=columns+3)
myfunction <- function(frame,columns){
athing = 0
if(columns == 5){
athing = 100
}
else{
athing = 1000
}
value[colums+1] = athing
return(value)}
Run Code Online (Sandbox Code Playgroud)
有问题的for循环看起来像这样:
columns = 6
for(i in 1:nrow(myframe){
values <- myfunction(as.matrix(myframe[i,]), columns)
values[columns+2] = i
values[columns+3] = myframe[i,3]
#more columns added with simple operations (i.e. sum)
solution <- rbind(solution,values)
#solution is a large matrix from outside the for-loop
} …Run Code Online (Sandbox Code Playgroud) 我想保存一组不断变化的 ggplot 是不同的文件。为此,我使用了一个看起来像这样的 for 循环:
save = c("plot1","plot2")
for (i in 1:length(save)){
ggsave(cat(save[i],"\n"), file="i.pdf")
}
Run Code Online (Sandbox Code Playgroud)
“plot1”和“plot2”正在工作 ggplots(=绘图对象的名称)。因为我收到以下错误:
Error in ggsave(cat(save[i], "\n"), file = "i.pdf") :
plot should be a ggplot2 plot
Run Code Online (Sandbox Code Playgroud)
我尝试了 cat 功能。无论是否使用该函数,它都会返回相同的错误。如果我直接输入“情节”,它会起作用......
我究竟做错了什么?
(编辑了示例,因此有多个情节)