String 在每行上循环并将每个单词存储在一行中,然后在R中生成一个数据帧
我有以下文件:String 在每行上循环并将每个单词存储在一行中,然后在R中生成一个数据帧,string,r,loops,dataframe,String,R,Loops,Dataframe,我有以下文件: [1]/tI /tam /tCharlotte [2]/ti /tam /tcharlotte [3]/tYou /tare /tsmart [4]/tyou /tare /tsmart 我希望输出数据帧具有以下形式: word gloss I i am am Charlotte charlotte You you are are smart
[1]/tI /tam /tCharlotte
[2]/ti /tam /tcharlotte
[3]/tYou /tare /tsmart
[4]/tyou /tare /tsmart
我希望输出数据帧具有以下形式:
word gloss
I i
am am
Charlotte charlotte
You you
are are
smart smart
有可能为此编写代码吗?我需要按制表符分隔文件吗 你的问题并不完全清楚。比如说,
##Read in the data.
tmp = read.table(textConnection("/tI /tam /tCharlotte
/ti /tam /tcharlotte
/tYou /tare /tsmart
/tyou /tare /tsmart"), sep="\n", stringsAsFactors=FALSE)
##Take the odd rows
##gsub: remove white space
##strsplit: split the string on "\t"
##unlist: go from a list to a vector
c1 = unlist(
strsplit(
gsub(" ", "", tmp[seq(1,nrow(tmp), 2),]), "/t"))
##Ditto the even rows
c2 = unlist(
strsplit(
gsub(" ", "", tmp[seq(2,nrow(tmp), 2),]), "/t"))
这为我们提供了两个向量,我们可以将它们放入数据帧中:
dd = data.frame(c1 = c1, c2 = c2)
structure(
as.data.frame(
lapply(
lapply(list(c(TRUE, FALSE), c(FALSE, TRUE)),
function(y) lapply(strsplit(
apply(dat, 1, "paste", collapse = ""), "/t"),
function(x) x[nchar(x) > 0])[y]),
unlist)),
.Names = c("word", "gloss"))
我想您不需要空行,所以只需删除它们:
dd[apply(dd, 1, function(i) sum(nchar(i))>0),]
此解决方案类似于@csgillespie的解决方案,但每次都是在一个命令中完成的(一旦读取了数据) 读取数据:
dat <- read.table(text = "/tI /tam /tCharlotte
/ti /tam /tcharlotte
/tYou /tare /tsmart
/tyou /tare /tsmart", stringsAsFactors = FALSE)
是[1]、[2]、。。。是文件的一部分还是仅仅从R输出?“/t”应该是制表符吗?在大多数语言中都是“\t”。嗨!谢谢你的代码!我的实际文件比那更复杂。所以在奇数行中,有来自某种语言(不是英语)的单词,在偶数行中,每个单词都有英语翻译。文件中总共有1200行。我想制作一个数据框,其中每个单词及其英文翻译都是成对的。如果行是成对的,那么重复
rbind(t(mydata[1:2,])、t(mydata[2:3,])
就可以了。显然,您需要一个循环或*在N/2行对上应用函数。