我正在尝试合并数据框中的列,以便它们为我提供一定的字符串。我将标题为“C”,“H”,“O”,“N”和“S”的列作为元素。这些列中列出了该分子中元素的数量,但是我想根据它们的值排除一些元素。例如,当没有氧气时,该值为0,因此在组合元素以组成字符串时,我想排除此值。

#This is a portion of my data frame titled data4a
C H O N S
3 4 0 0 1
7 5 4 1 0

#The code I have is
data4a$NewComp = paste("C",data4a$Total.C,"H", data4a$NewH, "O", data4a$O, "N", data4a$N, "S", data4a$S, sep = "")

#This code gives me this
C H O N S NewComp
3 4 0 0 1 C3H4O0N0S1
7 5 4 1 0 C7H5O4N1S0

#I expect to see something like this when I print my results
C H O N S NewComp
3 4 0 0 1 C3H4S1
7 5 4 1 0 C7H5O4N

#I want values of zero to be excluded from the string created

最佳答案

选项是带有参数applyMARGIN = 1

dat$NewComp <- apply(dat, 1, function(x) {
  tmp <- unlist(x)
  paste0(names(x)[tmp != 0], tmp[tmp != 0], collapse = "")
  })

结果
dat
#  C H O N S  NewComp
#1 3 4 0 0 1   C3H4S1
#2 7 5 4 1 0 C7H5O4N1

数据
dat <- structure(list(C = c(3L, 7L), H = 4:5, O = c(0L, 4L), N = 0:1,
    S = c(1L, 0L)), .Names = c("C", "H", "O", "N", "S"), class = "data.frame", row.names = c(NA,
-2L))

09-11 20:31