【问题标题】:Importing multiple lines of same observation in R在R中导入多行相同的观察
【发布时间】:2016-05-14 08:27:17
【问题描述】:

我正在尝试导入类似这样的数据

ID,time1,time2,time3,time4,time5,time6,time7,time8,time9,time10,
123456,
0.123425,0.543565,0.43543,0.34567,0.76543,12345,43567,43567,324567,324567,
87654,
0.14567,0.543123,0.435987,0.5675,0.58843,.5543,.567,.3567,.24567,.533367,
32156,

我试过这样导入它:

tmp <- read.csv(file, header = TRUE, sep = ",")

我也试过 read.table。 但是,一旦我尝试导入它,ID 就会被赋予它自己的观察结果,而所有其他变量都标记为缺失。下一行数据将 time1 插入 ID,将 time2 插入 time1,依此类推。

它看起来像:

ID       time1     time2    time3   .....
123456
0.123435 0.543565  0.43543  0.34567
87654
0.14567  0.543123  0.435987 0.5675

我希望我的输出如下所示:

ID     time1    time2    time3   ......
123456 0.123425 0.543565 0.43543
87654  0.14567  0.543123 0.435987
32156

【问题讨论】:

  • 一旦我尝试导入它 .. 你是如何导入它的?
  • tmp
  • 很好,现在将这些添加到问题中。
  • 是read.csv的输出吗?或者你想显示相同的输出?
  • 问题出在数据上。它在ID 字段之后有一个换行符。换行符必须完整的数据行之后。

标签: r


【解决方案1】:

假设所有数据的结构都相似,您可以在 R 中进行变通。对于这个例子,我假设导入的数据集中有偶数行(我已经删除了第五行进行测试)。

#remove empty column
dat <- dat[,1:11]

#create vector of identifiers to split by, each id repeated twice
ID2 <- rep(1:(nrow(dat)/2), each=2)

然后我们按标识符拆分数据,并提取我们需要的数据。这是第一行的第一个值,以及第二行的所有值(最后一个空值除外)。然后我们给向量原始数据的列名并返回它。

res <- lapply(split(dat,ID2), function(x){
  res <- c(x[1,1],x[2,-ncol(x)]) #remove final empty column
  names(res) <- colnames(dat)
  res
})

最后,我们把它绑定在一起

output <- do.call(rbind,res)

> output
  ID     time1    time2    time3    time4   time5   time6  time7 time8  time9   time10  
1 123456 0.123425 0.543565 0.43543  0.34567 0.76543 12345  43567 43567  324567  324567  
2 87654  0.14567  0.543123 0.435987 0.5675  0.58843 0.5543 0.567 0.3567 0.24567 0.533367

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-02-01
    • 1970-01-01
    • 2017-06-04
    • 2017-10-09
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多