R在for循环中赋值变量
问题描述:
我正在R中使用for循环来创建新的向量。 '文件'包含多个或多于500行的多个数据帧。R在for循环中赋值变量
temp = list.files(pattern="*txt")
files = lapply(temp, read.delim)
pos = c(1:100)
results = null
for (i in pos) {
nameA = paste("A", i, sep = "_")
nameC = paste("C", i, sep = "_")
resA = assign(nameA, unlist(lapply(files, function(x) x$perA[x$position==i])))
resC = assign(nameC, unlist(lapply(files, function(x) x$perC[x$position==i])))
cbind(summary(resA), results) #incorrect
cbind(summary(resC), results) #incorrect
}
现在我想执行的萨& RESC“摘要”在“排名”的所有值。我想把这些结果放在1个数据帧(结果)中。我现在该怎么做?
答
有点沿着这些线路:
# create a data.frame with 6 rows(since summary() returns a vector of 6 elements
df <- data.frame(1:6)
# set the rownames of df
rownames(df) = names(summary(1:6))
for (i in pos) {
nameA = paste("A", i, sep = "_")
...
xA = unlist(lapply(files, function(x) x$perA[x$position==i]))
xC = unlist(lapply(files, function(x) x$perC[x$position==i]))
df = cbind(df, as.numeric(summary(xA)), as.numeric(summary(xC)))
assign(nameA, xA)
assign(nameC, xC)
}
# set the column names of df
df[1] = NULL # initial column removed
colnames(df) = c("id", paste0("summary",c("A","C"), rep(1:100, each = 2)))
+0
它回答你的问题吗? –
答
是否有一个原因,以节省自己的,而不是一个列表内的每个向量?这将使进一步的分析更容易。
我们仍然可以将您的向量与mget
组合成一个列表。然后将summary
函数应用于此列表并使用cbind()
将结果组合为单个矩阵。
list_A <- mget(ls(pattern="A_[0-9]"))
list_C <- mget(ls(pattern="C_[0-9]"))
summary_A <- do.call(cbind,lapply(list_A,summary))
summary_C <- do.call(cbind,lapply(list_C,summary))
summary_All <- data.frame(summary_A, summary_C)
当然你要小心是否有与环境中相同的命名模式的其他对象。
所以基本上200列 - 名称A和名称C 100 pos 100到1右? –
在'for'循环的每次迭代中使用'cbind()' –
@ joel.wilson:回答你的第一个问题:的确如此。第二条评论:好的,但我不能只在for循环中执行sum = summary(nameA)。 – user1987607