【发布时间】:2021-10-30 01:54:55
【问题描述】:
我在将 for 循环的结果输出到 R 中的列表/向量时遇到问题。循环在如下结构的 df 上运行,其中每个唯一 ID 由 1 到 n 行表示:
id <- c(1, 2, 2, 2, 3, 4, 5, 6)
string <-c("apple", "grape", "orange", "blueberry", "plum", "tomato", "pear", "plum")
df <- data.frame(id, string)
对于每个唯一 ID,我想编写一个列表,将 n 行折叠成一行,其中包含基于“字符串”列中的信息的连接字符串。所以我有:
#write a function to concatenate strings where d = dataframe, n = column name, and s = character to act as separator
concat <- function(d, n, s) {
list_value = paste0(d[[n]], sep = s)
return(list_value)
}
#create two empty lists
string_list <- list()
item_list <- list()
#loop the concatenate function over each unique id in the df
for (i in unique(df$id)) {
item <- filter(df, id == i)
print(item)
item_list[i] <- item
strings <- concat(item, "string", ";")
print(strings)
string_list[i] <- strings
}
我可以从打印语句中看到循环“正确”运行(我正在将输出打印到控制台)但我收到警告“要替换的项目数不是替换长度的倍数" 并且 string_list 和 item_list 是不可能的大对象(约 2000 行的 df 变成了约 10M 元素的列表)。
如果在循环开始时我会说:
for (i in 1:length(df$id))
我得到一个长度与原始 df 中的行数相同的列表;但它是空的(它为所有返回整数 [0] 或字符 [1])。原始 df 中没有 NA(使用 table(is.na(df$col_name)) 检查所有列)。相同的警告。
使用 string_list
我错过了一些简单的东西。它是什么? 谢谢
编辑:我想我看到了问题的一部分。对象“项目”是一个(小)df,将一系列 df 附加到列表中会产生一个大对象。但是将 item_list
item_data <- data.frame(Col1 = integer(), Col2 = character(), stringsAsFactors = FALSE)
给出错误,新列会在现有列之后留下孔
【问题讨论】:
-
尝试将您的
item_list[和string_list[分配转换为[[。 -
string_list和item_list到底应该是什么?
-
你的意思是 item_list[[i]
-
@denisafonin 的目标是让 string_list 成为 ("apple;", "grape;" "orange;" "blueberry;", "plum;", "tomato;", "pear;" , "plum;") 和 item_list 为 (1, 2, 3, 4, 5, 6) 以便它们可以重新加入 df2