这是我之前提到的这个问题的后续问题:R for loop: create a new column with the count of a sub str from a different column
我有一张大桌子(100多个柱子,50k +行)。其中一列包含以下格式的数据:
col
chicken
chicken,goat
cow,chicken,goat
cow
我想:
col col2 col3
chicken
chicken goat
cow chicken goat
cow
有很多超过3列需要填充,我只是将其剥离为一个例子。我的脚本创建了适当数量的要填充的列,我只需要代码,我假设它是一个for循环,将'col'中的字符串拆分为','然后将拆分字符串放入后续列中。
感谢您的帮助!
答案 0 :(得分:11)
read.table(text="chicken
chicken,goat
cow,chicken,goat
cow", fill=TRUE, sep=",")
# Trivial to change the names of dataframe columns
V1 V2 V3
1 chicken
2 chicken goat
3 cow chicken goat
4 cow
答案 1 :(得分:3)
你可以试试这个:
library(splitstackshape)
concat.split(data = df, split.col = 1, sep = ",", drop = TRUE)
# col_1 col_2 col_3
# 1 chicken
# 2 chicken goat
# 3 cow chicken goat
# 4 cow