r - 使用循环获取子字符串并将其存储在变量中

标签 r

我的问题包括分割路径,获取所有子路径直到下一个“$”出现(一种累积子路径)并为每个子路径生成一个新变量。

一步一步地做,我得到了想要的输出:

data<-data.frame(path=c("A/A/$/B/$/A/$","B/C/$","B/C/$/C/$/A/B/$"),stringsAsFactors=FALSE)
library(stringr)
data$tr<-str_count(data$path,"\\$")
data$tr_1<-substr(sapply(strsplit(data$path, "\\$"), `[[`, 1),1,nchar(sapply(strsplit(data$path, "\\$"), `[[`, 1))-1)
data$tr_2<-ifelse(is.na(sapply(strsplit(data$path, "\\$"), `[`, 2))==TRUE,
                  "",
                  paste0(data$tr_1,substr(sapply(strsplit(data$path, "\\$"), `[`, 2),1,nchar(sapply(strsplit(data$path, "\\$"), `[`, 2))-1)))
data$tr_3<-ifelse(is.na(sapply(strsplit(data$path, "\\$"), `[`, 3))==TRUE,
                  "",
                  paste0(data$tr_2,substr(sapply(strsplit(data$path, "\\$"), `[`, 3),1,nchar(sapply(strsplit(data$path, "\\$"), `[`, 3))-1))) 

Doing it manually:

尝试根据 Creating new named variable in dataframe using loop and naming convention 在循环中执行相同操作,输出失败。

data<-data[,-c(4,5)]
for (i in 2:max(data$tr)) {
  data[[paste0("tr_",i)]]<-ifelse(is.na(sapply(strsplit(data$path, "\\$"), `[`, i))==TRUE,
                  "",
                  paste0(data$tr_i-1,substr(sapply(strsplit(data$path, "\\$"), `[`, i),1,nchar(sapply(strsplit(data$path, "\\$"), `[`, i))-1)))
}

Doing it in a loop:

还有其他递归方式吗? (每个新变量都使用前一个变量)。
提前致谢!

最佳答案

我会这样做:

data<-data.frame(path=c("A/A/$/B/$/A/$","B/C/$","B/C/$/C/$/A/B/$"),stringsAsFactors=FALSE)

#split strings
tmp <- strsplit(data$path, "/$", fixed = TRUE) #thanks to David
data$tr <- lengths(tmp)

#paste them together cumulatively
tmp <- lapply(tmp, Reduce, f = paste0, accumulate = TRUE)

#create data.frame
tmp <- lapply(tmp, `length<-`, max(lengths(tmp)))
tmp <- setNames(as.data.frame(do.call(rbind, tmp), stringsAsFactors = FALSE), 
                paste0("tr_", seq_len(max(data$tr))))

data <- cbind(data, tmp)
#             path tr tr_1  tr_2      tr_3
#1   A/A/$/B/$/A/$  3  A/A A/A/B   A/A/B/A
#2           B/C/$  1  B/C  <NA>      <NA>
#3 B/C/$/C/$/A/B/$  3  B/C B/C/C B/C/C/A/B

如果必须,您可以在另一个 lapply 循环中将 NA 值替换为空字符串。

关于r - 使用循环获取子字符串并将其存储在变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41608587/

相关文章:

r - 如果R中面积已知,如何找到积分的上限?

r - 在Docker Plumber中使用R预测包

R + ggplot + pdf 设备 + LaTeX : is it possible to embed fonts one time

r - 当存在关联时如何用 1 和 0 填充矩阵

r - 用矢量按列填充数据框

mysql - 使用 sprintf 将变量插入 SQL 查询时出现问题

python - 在特征向量中估算多个缺失值

r - 如何将 MVN 包的输出获取到 R 中的表中?

r - 在 R 中寻找更好的方法来按字段的一部分进行分组

r - 为 ggpaired 添加抖动