R:将字符串拆分为新行和新列
输入:R:将字符串拆分为新行和新列,r,R,输入: 我尝试过gsub/string拆分,但意识到输入新行和新列是另一个问题。感谢使用strsplit和sub id food_type 12 chinese 13 italian 14 spanish tmp嘿,签出这个解决方案,我希望它能帮助你 tmp <- "(12,'chinese'),(13,'italian'),(14,'spanish')" terms <- strsplit(tmp, "(?<=\\)),(?=\\()", perl=T
我尝试过gsub/string拆分,但意识到输入新行和新列是另一个问题。感谢使用strsplit和sub
id food_type
12 chinese
13 italian
14 spanish
tmp嘿,签出这个解决方案,我希望它能帮助你
tmp <- "(12,'chinese'),(13,'italian'),(14,'spanish')"
terms <- strsplit(tmp, "(?<=\\)),(?=\\()", perl=TRUE)
df <- lapply(terms[[1]], function(x) {
id <- sub("^\\(([^,]*).*", "\\1", x)
food_type <- sub(".*,'(.*)'\\)", "\\1", x)
z <- c(id, food_type)
return(z)
})
df <- do.call(rbind.data.frame, df)
names(df) <- c("id", "food_type")
df
id food_type
1 12 chinese
2 13 italian
3 14 spanish
下面是一个基于eval(parse(text=)
的解决方案,方法是将字符串转换为表达式:
tmp1=gsub("\\'","",gsub("\\(","",unlist(strsplit(unlist(strsplit(tmp,",")),"\\)"))))
id=as.numeric(tmp1[seq(1,length(tmp2),2)])
fooditem=tmp1[seq(0,length(tmp2),2)]
res=data.frame(id,fooditem)
id fooditem
1 12 chinese
2 13 italian
3 14 spanish
x我正在寻找一种方法来更改输入
并使用read.table
函数来获得所需的输出。最后的步骤是:
x <- eval(parse(text = paste0('list(', gsub('\\(', 'c\\(', tmp), ')')))
res <- as.data.frame(do.call(rbind, x), stringsAsFactors = FALSE)
names(res) <- c('id', 'food_type')
res
# id food_type
# 1 12 chinese
# 2 13 italian
# 3 14 spanish
df您能提供更多的信息吗?您试图用哪种编程/脚本语言编写解决方案?我是否可以假设tmp是一个文件的名称,其中包含您希望处理的数据,并且您希望将该文件传递给程序/脚本?如果满足要求,请接受该解决方案
x <- eval(parse(text = paste0('list(', gsub('\\(', 'c\\(', tmp), ')')))
res <- as.data.frame(do.call(rbind, x), stringsAsFactors = FALSE)
names(res) <- c('id', 'food_type')
res
# id food_type
# 1 12 chinese
# 2 13 italian
# 3 14 spanish
df <- lapply(strsplit(tmp, "\\(|\\)\\,?", perl = TRUE), function(x){
x <- x[x != ""]
read.table(text = paste0(x), sep = ",", header = FALSE, stringsAsFactors = FALSE)
})
df <- do.call(rbind, df)
names(df) <- c("id", "food_type")
# Result:
#> df
# id food_type
#1 12 chinese
#2 13 italian
#3 14 spanish