简体   繁体   English

覆盖/附加到R data.frame中的多值列

[英]Overwrite/append to multiple-value column in R data.frame

I have a data frame which contains a column in which I want to put multiple values (it can have a different amount of values per record). 我有一个数据框,其中包含一列,我想在其中放置多个值(每个记录可以有不同数量的值)。

I'm trying to append data to it using a for loop but it keeps giving the error: 我正在尝试使用for循环将数据追加到它,但是它不断给出错误:

Error in `[<-.data.frame`(`*tmp*`, 1, "piet", value = c(1, 2)) : 
replacement has 2 rows, data has 1

Is it impossible to overwrite/append to this column? 是否不可能覆盖/附加到此列? Small example code: 小示例代码:

a = data.frame(piet=numeric())
a[1,'piet'] = c(1)
a[1,'piet'] = c(1,2) # this throws the error

I realise there are better ways than using a for loop, but my data is spread out somewhat randomly over multiple .csv files (of which some have overlapping records, whose results I'm trying to combine here). 我意识到有比使用for循环更好的方法,但是我的数据多少随机分布在多个.csv文件中(其中某些文件具有重叠的记录,在此尝试合并其结果)。

Ok this is really weird but it works using list(c()) (thanks @Frank) and a very specific coding format: 好的,这确实很奇怪,但是它可以使用list(c()) (感谢@Frank)和非常特定的编码格式来工作:

a = data.frame(piet=list()) #initialize data frame
a[1,'piet'] = '' # create first row
a$piet[c(T)] = list(c(1,2,3)) # overwrite with list
a$piet[c(T)] = list(c(4,5,6)) # overwrite with new list
a$piet[c(T)] = list(c(unlist(a[1,'piet']),8,9)) # append to existing list

final contents of a: 最终内容:

> a
           piet
1 4, 5, 6, 8, 9

Note that the a$piet[row selection] is mandatory as well as using list(c()) ! 注意a$piet[row selection]是强制性的, a$piet[row selection]使用list(c())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM