在R的新行中分隔 Dataframe 中的条目[重复]

pgky5nke  于 2023-01-28  发布在  其他
关注(0)|答案(1)|浏览(149)
    • 此问题在此处已有答案**:

Split comma-separated strings in a column into separate rows(6个答案)
4天前关闭。
我有data.framedf在下面。

df <- data.frame(id = c(1:12),
               A = c("alpha", "alpha", "beta", "beta", "gamma", "gamma", "gamma", "delta", 
                     "epsilon", "epsilon", "zeta", "eta"),
               B = c("a", "a; b", "a", "c; d; e", "e", "e", "c; f", "g", "a", "g; h", "f", "d"),
               C = c(NA, 4, 2, 7, 4, NA, 9, 1, 1, NA, 3, NA),
               D = c("ii", "ii", "i", "iii", "iv", "v", "viii", "v", "viii", "i", "iii", "i"))

'B'列包含四个带分号的条目。我如何复制这些行中的每一行,并在'B'列中输入每个单独的值?
预期结果df2为:

df2 <- data.frame(id = c(1, 2, 2, 3, 4, 4, 4, 5, 6, 7, 7, 8, 9, 10, 10, 11, 12),
               A = c(rep("alpha", 3), rep("beta", 4), rep("gamma", 4), "delta", rep("epsilon", 3), 
                     "zeta", "eta"),
               B = c("a", "a", "b", "a", "c", "d", "e", "e", "e", "c", "f", "g", "a", "g", "h", "f", "d"),
               C = c(NA, 4, 4, 2, 7, 7, 7, 4, NA, 9, 9, 1, 1, NA, NA, 3, NA),
               D = c("ii", "ii", "ii", "i", "iii", "iii", "iii", "iv", "v", "viii", "viii", "v", "viii", "i", "i", "iii", "i"))

我试过了,但没成功:

df2 <- df
 # split the values in column B
 df2$B <- unlist(strsplit(as.character(df2$B), "; "))
 # repeat the rows for each value in column B
 df2 <- df2[rep(seq_len(nrow(df2)), sapply(strsplit(as.character(df1$B), "; "), length)),]
 # match the number of rows in column B with the number of rows in df2
 df2$id <- rep(df2$id, sapply(strsplit(as.character(df1$B), "; "), length))
 # sort the dataframe by id
 df2 <- df2[order(df2$id),]
c9qzyr3d

c9qzyr3d1#

我们可以在这里使用separate_rows-将sep指定为;,后跟零个或多个空格(\\s*)以扩展行

library(tidyr)
df_new <- separate_rows(df, B, sep = ";\\s*")
  • 检查预期OP
> all.equal(df_new, df2, check.attributes = FALSE)
[1] TRUE

base R中,我们可以通过list输出的lengths复制行序列

lst1 <- strsplit(df$B, ";\\s+")
df_new2 <- transform(df[rep(seq_len(nrow(df)), lengths(lst1)),], B = unlist(lst1))
row.names(df_new2) <- NULL

相关问题