【问题标题】:R "melt-cast" like operationR“熔铸”类操作
【发布时间】:2013-11-11 22:25:14
【问题描述】:

我有一个文件包含这样的内容:

name: erik
age: 7
score: 10
name: stan
age:8
score: 11
name: kyle 
age: 9
score: 20
...

如您所见,文件中的每条记录实际上包含 3 行。我想知道如何读取文件并转换为数据数据框,如下所示:

name    age    score
erik    7      10
stan    8      11
kyle    9      20
...

到目前为止我做了什么(感谢 tcash21):

> data <- read.table(file.choose(), header=FALSE, sep=":", col.names=c("variable", "value"))
> data
variable  value
1     name   erik
2      age      7
3    score     10
4     name   stan
5      age      8
6    score     11
7     name  kyle 
8      age      9
9    score     20

我在想如何通过 : 将列分成两列,然后在 reshape 包中使用类似 cast 的东西来做我想做的事? 或者我怎样才能得到只有索引号1,4,7,...的行,它有一个恒定的步长

谢谢!

【问题讨论】:

  • 首先,您应该使用read.table 和sep=":" 读取文件,这样您就可以将每个变量放在2 个单独的列中。
  • 使用?strsplit,拆分然后融化。

标签: r reshape reshape2


【解决方案1】:

另一种可能性:

library(reshape2)
df$id <- rep(1:(nrow(df)/3), each = 3)
dcast(df, id ~ variable, value.var = "value")

#   id age  name score
# 1  1   7  erik    10
# 2  2   8  stan    11
# 3  3   9  kyle    20

【讨论】:

    【解决方案2】:

    如果格式是可预测的,你可能想做一些非常简单的事情,比如

    # recreate data
    data <- as.matrix(c("erik",7,10,"stan",8, 11,"kyle",9,20),ncol=1)
    
    # get individual variables
    names <- data[seq(1,length(data)-2,3)]
    age <- data[seq(2,length(data)-1,3)]
    score <- data[seq(3,length(data),3)]
    
    # combine variables
    reformatted.data <- as.data.frame(cbind(names,age,score))
    

    【讨论】:

      猜你喜欢
      • 2019-02-08
      • 1970-01-01
      • 1970-01-01
      • 2017-06-24
      • 2016-12-18
      • 1970-01-01
      • 1970-01-01
      • 2011-09-17
      • 1970-01-01
      相关资源
      最近更新 更多