Replace values in data frame with other values according to a rule

前端 未结 4 1421
时光说笑
时光说笑 2020-12-16 15:19

I am an beginner in R and don`t find a solution for the following problem. Any help would be really appreciated!

I have a data.frame and want to replace certain valu

相关标签:
4条回答
  • 2020-12-16 15:57

    merge() might also be of help.

    yearend<-c("19921231","19931231","19941231")
    year<-c("1992","1993","1994")
    map = data.frame(yearend,year)
    
    merge(dataframe,map,by.x='date',by.y='yearend')
    
    0 讨论(0)
  • 2020-12-16 15:58

    A nice function is mapvalues() from the plyr package:

    require(plyr)
    dataframe$newdate <- mapvalues(dataframe$date, 
              from=c("19921231","19931231","19941231"), 
              to=c("1992","1993","1994"))
    
    0 讨论(0)
  • 2020-12-16 15:58

    You can use match:

    dataframe <- transform(dataframe, Year = year[match(date, yearend)])
    
          date variable value Year
    1 19921231        a     1 1992
    2 19931231        a     2 1993
    3 19941231        a     3 1994
    4 19941231        b     4 1994
    5 19931231        b     5 1993
    6 19941231        b     6 1994
    
    0 讨论(0)
  • 2020-12-16 15:59

    When you want to extract the year from the date, you can do this with the following line of code:

    dataframe$year <- substr(dataframe$date,1,4)
    

    When you want assign a class to the new variable simulataniously:

    dataframe$year <- as.integer(substr(dataframe$date,1,4))
    
    0 讨论(0)
提交回复
热议问题