当条目本身的值为零并且条目之前的条目为0时,跳过paste0条目

时间:2017-01-20 20:15:39

标签: r string

使用Form1功能时遇到一个问题。我有一个数据框: 数据:

Form1.Score

使用

paste0

我得到公式栏

    C  C13 H O N
1   1   0  4 0 0
2   2   0  4 0 0
3   3   0  4 0 0
4   4   0  4 0 0
5   5   0  4 1 0
6   1   1  4 1 0
7   2   1  4 1 1

问题是我希望所有字符串都有0值,所以对于第1行我想要:data$formula = paste0("C", data$C, "C13", data$C13, "H", data$H, "O", data$O, "N",data$N) 而不是 C C13 H O N formula 1 1 0 4 0 0 C1C130H4O0N0 2 2 0 4 0 0 C2C130H4O0N0 3 3 0 4 0 0 C3C130H4O0N0 4 4 0 4 0 0 C4C130H4O0N0 5 5 0 4 1 0 C5C130H4O1N0 6 1 1 4 1 0 C1C131H4O1N0 7 2 1 4 1 1 C2C131H4O1N1 ,依此类推。

我是R的新手所以我试过

C1H4

但这只给我真正的错误输出......

有谁可以帮助我,请或者知道如何解决这个问题?

非常感谢!

2 个答案:

答案 0 :(得分:2)

我认为只需一次申请即可!

逻辑:首先我们使用apply(df, 1, ...)遍历每一行;然后我们使用which检查所有条目是否为非零;获得索引后,只需将相应的名称和值进行分组

df$formula <- apply(df, 1, function(x){y = which(x!=0) 
                                       paste0(colnames(df)[y], x[y], collapse = "")})
# [1] "C1H4"         "C2H4"         "C3H4"         "C4H4"         "C5H4O1"       "C1C131H4O1"   "C2C131H4O1N1" 

> df
#  C C13 H O N      formula
#1 1   0 4 0 0         C1H4
#2 2   0 4 0 0         C2H4
#3 3   0 4 0 0         C3H4
#4 4   0 4 0 0         C4H4
#5 5   0 4 1 0       C5H4O1
#6 1   1 4 1 0   C1C131H4O1
#7 2   1 4 1 1 C2C131H4O1N1  

答案 1 :(得分:1)

> apply(apply(data, 1, function(x) ifelse(x>0, paste0(names(data), x), '')), 2, paste0, collapse='')
             1              2              3              4              5              6              7 
        "C1H4"         "C2H4"         "C3H4"         "C4H4"       "C5H4O1"   "C1C131H4O1" "C2C131H4O1N1" 

可以将其分配回数据框中的列。

内部apply执行>0选择:

> apply(data, 1, function(x) ifelse(x>0, paste0(names(data), x), ''))
    1    2    3    4    5    6      7     
C   "C1" "C2" "C3" "C4" "C5" "C1"   "C2"  
C13 ""   ""   ""   ""   ""   "C131" "C131"
H   "H4" "H4" "H4" "H4" "H4" "H4"   "H4"  
O   ""   ""   ""   ""   "O1" "O1"   "O1"  
N   ""   ""   ""   ""   ""   ""     "N1" 

外部apply将此结果的列粘贴在一起以获得最终输出。