繁体   English   中英

在每列上使用Apply函数调整data.frame

[英]Using the apply function over each column for adjusting of data.frame

因此,我希望将14:18列更改为1列“类型”。 我想给这个新列中的每个条目(以匹配前面的观察)中5个中的哪个为1(因为只有1个可以为真)。 这是我在R中(以及沮丧的情况)的最佳尝试。

library(caret)
data("cars")

carSubset <- subset(cars)
head(carSubset)

# I want to convert the columns from of carSubset with following vector names
types <- c("convertible","coupe", "hatchback", "sedan", "wagon")

# into 1 column named Type, with the corresponding column name
carSubset$Type <- NULL
carSubset <- apply(carSubset[,types],
               2, 
               function(each_obs){
                   hit_index <- which(each_obs == 1)
                   carSubset$Type <- types[hit_index]
              })
head(carSubset) # output:
  1             2             3             4             5 
  "sedan"       "coupe" "convertible" "convertible" "convertible" 

这就是我想要的...但是,我也希望将data.frame的其余部分与之一起使用,就像我只想要“ Type”的新列一样,但是我什至无法使用以下代码行来访问它。 ..

head(carSubset$Type) # output: Error in carSubset$Type : $ operator is invalid for atomic vectors

在将以前相关的数据观测值附加该列时如何动态添加新列有任何帮助吗?

我真的想通了! 可能不是最好的方法,但是,它有效。

library(caret)
data("cars")

carSubset <- subset(cars)  
head(carSubset)

# I want to convert the columns from of carSubset with following vector names
types <- c("convertible","coupe", "hatchback", "sedan", "wagon")

head(carSubset[,types])
carSubset[,types]
# into 1 column named Type, with the corresponding column name
carSubset$Type <- NULL
newSubset <- c()
newSubset <- apply(carSubset[,types],
               1, 
               function(obs){
                   hit_index <- which(obs == 1)
                   newSubset <- types[hit_index]
              })
newSubset
carSubset$Type <- cbind(Type = newSubset)
head(carSubset[, !(names(carSubset) %in% types)])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM