2016-12-18 4 views
0

私の希望は列14:18を1列の "Type"に変更することです。私は、この新しい列の各エントリに、前の観測と一致させるために、5のどれが1であるかの値を与えたかったのです(そのうちの1つだけが真であるためです)。これはRでこれを行う上での私の最善の試みです(そして、不満を超えて)。私はちょうど「タイプ」の新しい列を望んでいたようdata.frameの調整のために各列に適用関数を使用する

私が欲しかったものである
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の残りの部分はそれと一緒に来たかったが、私もそれにアクセスすることはできません次のコード行...

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

どのように上の任意の助けを借りて、それに以前に関連するデータの観測を追加しながら、新しい列を動的に追加しますか?

答えて

0

私は実際にそれを理解しました!おそらくそれを行う最良の方法ではないが、ちょっと、それは動作します。

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)]) 
関連する問題