简体   繁体   中英

Error in recoding vars in R

I have imported from Excel a file that after being imported has the following str

str(mydata)
$ Injury   : chr  "MMCAI" "MMCAI" "MMCAI" "MMCAI" ...
$ Na_RR    : num  161 152 152 150 143 ...
$ place    : chr  "core" "core" "core" "core" ...

Now I want to create 5 different groups combining vars "Injury" and "place" I have this code

mydata$group[mydata$Injury=="MMCAI" & mydata$place=="core"]<- "IC"

However, after passing the code I got observations that are classified as NA ie:

 231    core    MMCAI   138.8168    3.253879    core    IC
 232    core    MMCAI   142.7655    3.096850    core    NA
 233    core    MMCAI   141.1135    3.066894    core    NA
 234    core    MMCAI   137.1993    2.922434    core    NA
 235    core    MMCAI   138.3765    2.848378    core    NA

I cannot find the error... Any help will be greatly appreciated

Thanks

If there are leading/lagging spaces for the concerned variables, this could happen

 mydata$group[with(mydata, Injury=='MMCAI' & place=='core')] <- 'IC'
 mydata
 #   Na_RR place  Injury group
 #1   231  core   MMCAI    IC
 #2   232  core  MMCAI   <NA>
 #3   233  core   MMCAI  <NA>
 #4   234  core  MMCAI   <NA>
 #5   235  core   MMCAI  <NA>
 #6   239  core   MMCPI  <NA>

When we remove the leading/lagging spaces, it should work

library(stringr)
mydata[c('place', 'Injury')] <- lapply(mydata[c('place', 'Injury')], str_trim)
mydata$group[with(mydata, Injury=='MMCAI' & place=='core')] <- 'IC'
mydata
#  Na_RR place Injury group
#1   231  core  MMCAI    IC
#2   232  core  MMCAI    IC
#3   233  core  MMCAI    IC
#4   234  core  MMCAI    IC
#5   235  core  MMCAI    IC
#6   239  core  MMCPI  <NA>

Other option would be to use grep without removing the spaces.

data

mydata <- structure(list(Na_RR = c(231L, 232L, 233L, 234L, 235L,
 239L), 
place = c("core", "core", "core", "core", "core", "core"), 
Injury = c("MMCAI", "MMCAI ", " MMCAI", " MMCAI ", " MMCAI", 
"MMCPI")), .Names = c("Na_RR", "place", "Injury"),
row.names = c(NA,-6L), class = "data.frame")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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