r分组数据框中用“ /”分隔的数字

时间:2019-01-25 09:37:15

标签: r strsplit

我有一个大型数据框,看起来像以下示例:

假设有一个球类游戏,您可以在其中扔球以击中目标并获得积分。有一支球队A和一支B,每个人都可以决定要掷球多少次(所以这是不平等的)。看起来像这样:

df<-data.frame("ID" = as.factor(c(1,2,3,4,5,6,7,8,9,10)),
               "Group" = c("A","A","A","A","A","B","B","B","B","B"),
               "Number_of_hits" = c(1,2,5,3,3,1,2,1,1,3),
               "Score_per_hit"=c("60","23.4/18.1","30/34.1/40/10.2/15.5","12/15.0/40","40/23.1/22","20.5","64.8/12.2","50","30","20/43.3/65"))

   ID Group Number_of_hits        Score_per_hit
   1     A              1                   60
   2     A              2            23.4/18.1
   3     A              5 30/34.1/40/10.2/15.5
   4     A              3           12/15.0/40
   5     A              3           40/23.1/22
   6     B              1                 20.5
   7     B              2            64.8/12.2
   8     B              1                   50
   9     B              1                   30
  10     B              3           20/43.3/65

现在,我希望以某种方式更改它,以便我可以使用计分功能,所以我希望它像这样:

   ID Group Score_per_hit
   1     A          60.0
   2     A          23.4
   2     A          18.1
   3     A          30.0
   3     A          34.1
   3     A          40.0
   3     A          10.2
   3     A          15.5
   4     A          12.0
   4     A          15.0
   4     A          40.0
   5     A          40.0
   5     A          23.1
   5     A          22.0
etc..

我已经{/ {1}}看过/尝试过一些东西,但是我只会出错。有人可以帮助我吗?非常感谢!

1 个答案:

答案 0 :(得分:0)

也许有一种更优雅的方法,但是这里有一个使用for循环的选项:

df2 <- vector("list", nrow(df))
for(i in seq(df2)){
  df2[[i]] <- expand.grid(
    ID = df$ID[i], 
    Group=df$Group[i], 
    Score_per_hit = as.numeric(
      strsplit(as.character(df$Score_per_hit[i]), "/", fixed = TRUE)[[1]])
  )
}
df2 <- do.call("rbind", df2)
df2