0
Follow
4
View

How to separate a column of directory paths and create a new column with the first level directory in r

dlstonefly 注册会员
6 days ago
 library(stringr)     
 
 df <- data.frame(lvl = c("levela1/levela2/levela3",
                     "levelb1/levelb2/levelb3",
                     "levelc1/levelc2/levelc3"))

 df <- cbind(str_split_fixed(df$lvl, '/', n=2), df[,-1])
czuf_zq 注册会员
6 days ago

It's unclear to me what you're looking to do precisely but you may want to try using strsplit(x, split = "/") and then index the output.

Edit:

Hey Lou_A, maybe the follwing is what you are looking. There are probably more elegant ways of doing this but this is what came to mind.

df <- data.frame(lvl = c("levela1/levela2/levela3",
                         "levelb1/levelb2/levelb3",
                         "levelc1/levelc2/levelc3"))

df[,"lvl1"] <- sapply(strsplit(df[,1], "/"), `[`, 1)

rep.fun <- function(str){
              lvl1 = strsplit(str, "/")[[1]][1]
              low.lvl = gsub(lvl1, "", str)
              return(low.lvl)
}

df[,"rest.lvl"] <- sapply(df[,1], rep.fun)