text to column, do not repeat column name
本问题已经有最佳答案,请猛点这里访问。
我有一个如下所示的 df:
|
1
2 3 4 |
id name grade
1 rich, tom, todd, 12 2 chris,mary 9 3 larry 10 |
我运行以下代码将文本拆分为列:
|
1
|
newdf <- within(df, name<-data.frame(do.call(‘rbind’, strsplit(as.character(name), ‘,’, fixed=TRUE))))
|
这是我的输出:
|
1
2 3 4 |
id name.X1 name.X2 name.X3 grade
1 rich tom todd 12 2 chris mary chris 9 3 larry larry larry 10 |
我的代码是重复名称(在 id 2
我们可以使用 splitstackshape
中的 cSplit
|
1
2 3 4 5 6 |
library(splitstackshape)
cSplit(df,”name”,”,”) # id grade name_1 name_2 name_3 #1: 1 12 rich tom todd #2: 2 9 chris mary NA #3: 3 10 larry NA NA |
如果我们使用 strsplit,由于 list 元素的长度不等,最好用 NA 填充,否则元素会重复。对于最后用 NA 填充,一个选项是获取每个 list 元素的 length,这可以用 lengths 完成,取 max (\\’mx\\’) 并分配 length 到 \\’mx\\’。然后,我们只需根据 \\’mx\\’ 在 \\’df\\’ 上创建新列。
|
1
2 3 4 5 6 7 8 |
lst <- strsplit(as.character(df$name),”,\\\\s*”)
mx <- max(lengths(lst)) df[paste0(“name”, seq(mx))] <- lapply(lst, `length<-`, mx) df[setdiff(names(df),”name”)] # id grade name1 name2 name3 #1 1 12 rich chris larry #2 2 9 tom mary <NA> #3 3 10 todd <NA> <NA> |
- @ZheyuanLi name_3: Factor w/ 1 level”todd”: 1 NA NA
- @ZheyuanLi 是的,因为前一种情况,列作为初始\\’name\\’列返回为factor,但在strsplit 中,它将是character 列。
- @ZheyuanLi 我猜对于 factor,NA 可能是 NA_integer_
- 完美运行,谢谢@akrun
- 对于 csplit (cSplit(df, “name”, “,”) 你可以用一行代码拆分多列吗?我尝试了几种变体,但对 cSplit 没有任何效果。我尝试了这样的事情: cSplit(df , “name”, “subject”, “,”) 但它不起作用。
- @richiepop2 为此,您需要连接,即 cSplit(df, c(“name”,”subject”),”,”)
- 啊,明白了。谢谢!!!
来源:https://www.codenong.com/38551942/
