简体   繁体   中英

Create a new column based on another column in R

I have a table as follows:

Name   ID   Level
Name1   A     1
Name2   B     2
Name3   C     3
Name4   D     1
Name5   E     2
Name6   F     1

Does anyone know how I can create another column in R which essentially looks at Col "Level" where I can highlight that a particular row belongs to the level 1 above it. eg in the above example Name2 and Name 3 belongs to the same group as Name1; Name 5 belongs to the Name 4 Group.

I can do this in Excel using if statements, but would be better if I can do all this within R. If not then it might be easier just to create the groupings in Excel then export it to R.

I would like it to look like this after:

Name   ID   Level  Groupings
Name1   A     1    Name1
Name2   B     2    Name1
Name3   C     3    Name1
Name4   D     1    Name4
Name5   E     2    Name4
Name6   F     1    Name6
etc     etc   etc  etc 

This part of code is just to re-create your dataset example:

data <- data.frame(Name = paste0('Name',1:6),
                   ID = LETTERS[1:6],
                   Level = c(1,2,3,1,2,1),
                   stringsAsFactors = FALSE) 

whereas the following part is one possible way to solve your issue, using the na.locf() function from the zoo package:

library(zoo)
data$Groupings <- ifelse(data$Level == 1, data$Name, NA) data$Groupings <- na.locf(data$Groupings)

For future question about code issues I suggest you to post on Stack Overflow instead of Data Science.

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