簡體   English   中英

如何遍歷R中的列名

[英]how to loop through column names in R

genres=c("Action","Adventure","Animation","Biography","Comedy","Crime",
 "Documentary","Drama","Family","Game.Show","Horror","Music","Musical",
 "Mystery","Romance","Sci.Fi","Short","Thriller","War","Western")

這是我的流派向量。

另一個數據集具有相同的列名。

這是數據集列名

"Title"        "Genre"        "imdbRating"   "Release_Year" 
"Action"       "Adventure"    "Animation"    "Biography"    "Comedy"    
"Crime"        "Documentary"  "Drama"        "Family" 
"Fantasy"      "Game.Show"    "Horror"       "Music"
"Musical"      "Mystery"      "N.A"          "Romance"
"Sci.Fi"       "Short"        "Sport"        "Thriller"   
"War"          "Western"  

我想為所有類型運行此命令,用值替換每個類型。

     data_predict$genres[grepl("*genres*", data_predict$Genre)]=1

Orignal Data set


        data_predict<-structure(list(Genre = structure(c(3L, 1L, 2L), .Label = c("Action, Adventure, Sci-Fi", 
"Action, Drama, War", "Sci-Fi"), class = "factor"), Action = c(0, 
0, 0), Adventure = c(0, 0, 0), Animation = c(0, 0, 0), Biography = c(0, 
0, 0), Comedy = c(0, 0, 0), Crime = c(0, 0, 0), Documentary = c(0, 
0, 0), Drama = c(0, 0, 0), Family = c(0, 0, 0), Game.Show = c(0, 
0, 0), Horror = c(0, 0, 0), Music = c(0, 0, 0), Musical = c(0, 
0, 0), Mystery = c(0, 0, 0), Romance = c(0, 0, 0), Sci.Fi = c(0, 
0, 0), Short = c(0, 0, 0), Thriller = c(0, 0, 0), War = c(0, 
0, 0), Western = c(0, 0, 0)), .Names = c("Genre", "Action", "Adventure", 
"Animation", "Biography", "Comedy", "Crime", "Documentary", "Drama", 
"Family", "Game.Show", "Horror", "Music", "Musical", "Mystery", 
"Romance", "Sci.Fi", "Short", "Thriller", "War", "Western"), row.names = c(NA, 
3L), class = "data.frame") 

預期結果

data_predicted<-structure(list(Genre = structure(c(3L, 1L, 2L), .Label = c("Action, Adventure, Sci-Fi", 
    "Action, Drama, War", "Sci-Fi"), class = "factor"), Action = c(0, 
    1, 1), Adventure = c(0, 1, 0), Animation = c(0, 0, 0), Biography = c(0, 
    0, 0), Comedy = c(0, 0, 0), Crime = c(0, 0, 0), Documentary = c(0, 
    0, 0), Drama = c(0, 0, 1), Family = c(0, 0, 0), Game.Show = c(0, 
    0, 0), Horror = c(0, 0, 0), Music = c(0, 0, 0), Musical = c(0, 
    0, 0), Mystery = c(0, 0, 0), Romance = c(0, 0, 0), Sci.Fi = c(0, 
    0, 0), Short = c(0, 0, 0), Thriller = c(0, 0, 0), War = c(0, 
    0, 1), Western = c(0, 0, 0)), .Names = c("Genre", "Action", "Adventure", 
    "Animation", "Biography", "Comedy", "Crime", "Documentary", "Drama", 
    "Family", "Game.Show", "Horror", "Music", "Musical", "Mystery", 
    "Romance", "Sci.Fi", "Short", "Thriller", "War", "Western"), row.names = c(NA, 
    3L), class = "data.frame")

嘗試

library(qdapTools)
mtabulate(strsplit(as.character(data_predict$Genre), ', '))

或者

 data_predict[-1] <- lapply(names(data_predict)[-1],
      function(x) as.numeric(grepl(x, data_predict$Genre)))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM