【问题标题】:writing out .dat file in r在 r 中写出 .dat 文件
【发布时间】:2020-01-28 18:04:38
【问题描述】:

我有一个如下所示的数据集:

ids <- c(111,12,134,14,155,16,17,18,19,20)
scores.1 <- c(0,1,0,1,1,2,0,1,1,1)
scores.2 <- c(0,0,0,1,1,1,1,1,1,0)

data <- data.frame(ids, scores.1, scores.1)

> data
   ids scores.1 scores.1.1
1  111        0          0
2   12        1          1
3  134        0          0
4   14        1          1
5  155        1          1
6   16        2          2
7   17        0          0
8   18        1          1
9   19        1          1
10  20        1          1

ids 代表学生 ID,scores.1 是第一个问题的响应/分数,scores.2 是第二个问题的响应/分数。学生 ID 的位数不同,但分数始终为 1 位数。我正在尝试通过生成一些对象并在gdata 库中的write.fwf 函数中使用这些对象来写出.dat 文件。

item.count <- dim(data)[2] - 1 # counts the number of questions in the dataset

write.fwf(data, file = "data.dat", width = c(5,rep(1, item.count)), 
          colnames = FALSE, sep = "")

我想用一些空格分隔学生 ID 和问题响应,所以我想为学生 ID 使用 5 个空格,并指定我在 write.fwf() 函数中使用了 width = c(5, rep(1, item.count))。但是,输出文件看起来像这样,在学生 ID 的左侧有空格

  11100
   1211
  13400
   1411
  15511
   1622
   1700
   1811
   1911
   2011

而不是在ids的右侧。

  111 00
   12 11
  134 00
   14 11
  155 11
   16 22
   17 00
   18 11
   19 11
   20 11

有什么建议吗?

谢谢!

【问题讨论】:

    标签: r save


    【解决方案1】:

    我们可以将uniteunite 'score' 列合并为一个,然后使用write.csv

    library(dplyr)
    library(tidyr)
    data %>% 
        unite(scores, starts_with('scores'), sep='')
    

    【讨论】:

    • 嗨@akrun,unitedplyr 中的函数吗?我收到此错误:Error in unite(., scores, starts_with("scores"), sep = "") : could not find function "unite"
    • @amisos55。对不起来自tidyr
    【解决方案2】:

    在@akrun 的帮助下,这给了我想要的:

    library(dplyr)
    library(tidyr)
    data %>% 
        unite(scores, starts_with('scores'), sep='')
    
    write.fwf(data, file = "data.dat", 
              width = c(5,item.count), 
              colnames = FALSE, sep = " ")
    

    在 .dat 文件中,数据集如下所示:

      111 00
       12 11
      134 00
       14 11
      155 11
       16 22
       17 00
       18 11
       19 11
       20 11
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-11-27
      • 1970-01-01
      • 2011-05-28
      • 2012-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多