在R中应用整行

时间:2014-09-20 18:31:09

标签: r

我有这样的文件,

"1" 10 2 0 0 0 0 0 0 0 0 0 0 0 4 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0
"2" 10 3 6 17 11 15 8 17 14 1 42 21 22 15 9 9 17 12 9 16 4 8 12 29 23 11 0 0 0 0
"3" 10 4 39 39 14 33 16 23 37 21 29 22 46 26 16 26 21 22 21 10 16 3 10 14 20 12 6 0 0 0
"4" 100 18 0 0 0 1 0 0 0 0 0 0 2 0 0 1 0 2 8 5 2 1 2 4 9 6 4 3 0 0
.....................

我正在尝试应用该功能,

mydat = c(10,2,0,19,20,19,0,0) #taken as an example
char10 = letters[1+(md %/% 10)] #actual code
char10[md==0] = 0

但是,我怎样才能在3:30的列上对原始文件应用它(第一列是行号,从那之后计算)。我应该先将每一行转换为一个列表,然后再进行操作吗?这需要更多时间。

编辑:输入结果(头(数据))

structure(list(V1 = c(3L, 4L, 9L, 10L, 10L, 10L), V2 = c(2L, 
3L, 2L, 2L, 3L, 4L), V3 = c(0L, 5L, 0L, 0L, 6L, 39L), V4 = c(0L, 
11L, 0L, 0L, 17L, 39L), V5 = c(0L, 9L, 0L, 0L, 11L, 14L), V6 = c(0L, 
10L, 0L, 0L, 15L, 33L), V7 = c(0L, 13L, 0L, 0L, 8L, 16L), V8 = c(0L, 
24L, 0L, 0L, 17L, 23L), V9 = c(0L, 39L, 0L, 0L, 14L, 37L), V10 = c(0L, 
18L, 0L, 0L, 1L, 21L), V11 = c(4L, 25L, 0L, 0L, 42L, 29L), V12 = c(3L, 
47L, 0L, 0L, 21L, 22L), V13 = c(3L, 35L, 0L, 0L, 22L, 46L), V14 = c(0L, 
34L, 0L, 4L, 15L, 26L), V15 = c(0L, 24L, 0L, 0L, 9L, 16L), V16 = c(0L, 
24L, 0L, 0L, 9L, 26L), V17 = c(0L, 27L, 0L, 1L, 17L, 21L), V18 = c(0L, 
22L, 0L, 0L, 12L, 22L), V19 = c(0L, 7L, 0L, 0L, 9L, 21L), V20 = c(0L, 
14L, 5L, 0L, 16L, 10L), V21 = c(0L, 3L, 4L, 0L, 4L, 16L), V22 = c(0L, 
0L, 0L, 0L, 8L, 3L), V23 = c(0L, 1L, 0L, 1L, 12L, 10L), V24 = c(0L, 
4L, 0L, 0L, 29L, 14L), V25 = c(0L, 7L, 0L, 0L, 23L, 20L), V26 = c(0L, 
14L, 1L, 0L, 11L, 12L), V27 = c(1L, 0L, 0L, 0L, 0L, 6L), V28 = c(6L, 
2L, 0L, 0L, 0L, 0L), V29 = c(0L, 2L, 0L, 0L, 0L, 0L), V30 = c(2L, 
0L, 0L, 0L, 0L, 0L)), .Names = c("V1", "V2", "V3", "V4", "V5", 
"V6", "V7", "V8", "V9", "V10", "V11", "V12", "V13", "V14", "V15",   
"V16", "V17", "V18", "V19", "V20", "V21", "V22", "V23", "V24", 
"V25", "V26", "V27", "V28", "V29", "V30"), row.names = c(1L, 
3L, 6L, 9L, 10L, 11L), class = "data.frame")

1 个答案:

答案 0 :(得分:0)

按行应用功能:

  m1 <- t(apply(data[,-(1:2)], 1, function(x) {
                     char10 <- letters[1+(x %/% 10)]
                     char10[x==0] <- 0
                     char10 }))

如果您需要使用paste并按行折叠上述内容

  unname(apply(m1, 1, paste, collapse=""))
  #[1] "00000000aaa0000000000000aa0a" "ababbcdbceddccccaba0aaab0aa0"
  #[3] "00000000000000000aa0000a0000" "00000000000a00a00000a0000000"
  #[5] "abbbabbaeccbaabbabaabccb0000" "ddbdbcdcccecbccccbbabbcba000"