Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
519 views
in Technique[技术] by (71.8m points)

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

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 values of a column with defined other values.

data.frame

date<-c("19921231","19931231","19941231","19941231","19931231","19941231")
variable<-c("a","a","a","b","b","b")
value<-c(1:6)
dataframe <- data.frame(date,variable,value)

attempt to solve problem

yearend<-c("19921231","19931231","19941231")
year<-c("1992","1993","1994")
map = setNames(yearend,year)
dataframe[] = map[dataframe]

error message

Error in map[dataframe] : invalid subscript type 'list'

The problem is obviously, that it is not a matrix. What is the most efficient way to solve this problem? It should also work if I want to replace "real" character, e.g. "BGSFDS" with "BASF stock".

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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"))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

Just Browsing Browsing

[1] html - How to create even cell spacing within a

2.1m questions

2.1m answers

60 comments

57.0k users

...