简体   繁体   English

r-具有多个列的ifelse(应用)

[英]r - ifelse with multiple columns (apply)

I am new to understanding the apply world and while i am starting to understand the concept, have trouble with the application. 我对理解apply世界是陌生的,而当我开始理解概念时,会对应用程序有麻烦。

i have multiple columns with "Y" in as a value that I would like to change to the last letter of the column name. 我有多个带有“ Y”的列,我想将其更改为列名的最后一个字母。

I would like to use the following to get a the list of columns to apply the function to: 我想使用以下内容获取将函数应用到的列的列表:

flaggs2015 <- grep("Flag", names(ItemStats_2015))

here is an example of what i would like to do with 1 column: 这是我想对1列进行处理的示例:

ItemStats_2015$Item_Flag_A <- ifelse(ItemStats_2015$Item_Flag_A == "Y", str_sub(flaggs2015[1], -1, -1), NA)

except i would, obviously, like to do it over any column with 'Flag' in the name at the same time. 当然,除了我显然想同时对名称中带有'Flag'任何列进行操作。

Here is sample data: 这是示例数据:

Item_ID Item_Flag_A     dummy column    Item_Flag_B     Item_Flag_C
54434   Y               red                         
85068                   green                           
85070   Y               purple                          Y       
85072                   orange                          
85074   Y               red                         
85078   Y               green                           
85080   Y               purple          Y           
85086                   orange                          
85088                   red                         

Im stuck with that: 我坚持这一点:

df <- data.frame(Item_ID = 1:3, Item_Flag_A = c("", "Y", ""), Dummy = 1:3, Item_Flag_B = c("Y", "", ""))
idx <- grep("Flag", names(df), value = T)

sapply(idx,  function(x) {
  df[, x] <<- ifelse(df[, x] == "Y", str_sub(x, -1, -1), NA)
})

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

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