如何用Base R一行代码拆分数据框中含斜杠的行?
Split Slash-Separated Rows into Individual Rows (Base R One-Liner)
Hey there! Let's start by confirming your original data frame:
mydf <- data.frame(a=c('A','B','C','D/E','F','G/H','I/J','K','L'), b=c(1,2,3,'4/5',6,'7/8','9/10',11,12)) mydf # a b # 1 A 1 # 2 B 2 # 3 C 3 # 4 D/E 4/5 # 5 F 6 # 6 G/H 7/8 # 7 I/J 9/10 # 8 K 11 # 9 L 12
Here's a tight one-liner using only Base R that transforms this into your desired mydf2:
mydf2 <- do.call(rbind, lapply(1:nrow(mydf), function(i) setNames(data.frame(strsplit(as.character(mydf$a[i]), "/")[[1]], strsplit(as.character(mydf$b[i]), "/")[[1]]), names(mydf))))
Let me break down the logic so you know what's going on:
lapply(1:nrow(mydf), ...)loops through every row of your data frame- For each row,
strsplit(as.character(col), "/")[[1]]splits the value in columnsaandbat the slash (we convert to character first since some values might be stored as factors) - We wrap those split results into a tiny data frame and use
setNamesto keep the original column names do.call(rbind, ...)stacks all those tiny data frames into a single, cleaned-up data frame
If you run that, you'll get exactly the output you wanted:
mydf2 # a b # 1 A 1 # 2 B 2 # 3 C 3 # 4 D 4 # 5 E 5 # 6 F 6 # 7 G 7 # 8 H 8 # 9 I 9 # 10 J 10 # 11 K 11 # 12 L 12
内容的提问来源于stack exchange,提问作者DaniCee
相关产品推荐
相关产品推荐

