相关疑难解决方法(0)

R Dataframe:按行,按行聚合列内的字符串

对于一个特殊问题,我有一个非常低效的解决方案.我有文本数据,由于各种原因,它以随机的间隔跨越数据帧的各行.然而,已知某些子集基于数据帧中其他变量的唯一组合而属于一起.例如,参见MWE演示结构和我的初始解决方案:

# Data
df <- read.table(text="page passage  person index text
1  123   A   1 hello      
1  123   A   2 my
1  123   A   3 name
1  123   A   4 is
1  123   A   5 guy
1  124   B   1 well
1  124   B   2 hello
1  124   B   3 guy",header=T,stringsAsFactors=F)

master<-data.frame()
for (i in 123:max(df$passage)) {
  print(paste0('passage ',i))
  tempset <- df[df$passage==i,]
  concat<-''
  for (j in 1:nrow(tempset)) {
    print(paste0('index ',j))
    concat<-paste(concat, tempset$text[j])
  }
  tempdf<-data.frame(tempset$page[1],tempset$passage[1], tempset$person[1], concat, stringsAsFactors = FALSE)
  master<-rbind(master, tempdf) …
Run Code Online (Sandbox Code Playgroud)

string r string-concatenation aggregate-functions dataframe

3
推荐指数
2
解决办法
3051
查看次数

如何使用数据表应用函数?

如何根据另一个变量的唯一值对一个或多个变量应用函数?就像是

dt[,DoStuff(x) ,y]
Run Code Online (Sandbox Code Playgroud)

考虑mpg来自ggplot2 的数据集

require(data.table)
require(ggplot2)
as.data.table(mpg)
     manufacturer  model displ year cyl      trans drv cty hwy fl   class
  1:         audi     a4   1.8 1999   4   auto(l5)   f  18  29  p compact
  2:         audi     a4   1.8 1999   4 manual(m5)   f  21  29  p compact
  3:         audi     a4   2.0 2008   4 manual(m6)   f  20  31  p compact
  4:         audi     a4   2.0 2008   4   auto(av)   f  21  30  p compact
  5:         audi     a4   2.8 1999   6   auto(l5)   f  16 …
Run Code Online (Sandbox Code Playgroud)

r data.table

1
推荐指数
1
解决办法
79
查看次数