根据规则将数据框中的值替换为其他值 [英] Replace values in data frame with other values according to a rule

查看:408
本文介绍了根据规则将数据框中的值替换为其他值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是R的初学者,不会为以下问题找到解决方案。任何帮助将非常感谢!



我有一个data.frame,并希望用定义的其他值替换列的某些值。



data.frame

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

试图解决问题

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

错误消息

 地图中的错误[dataframe]:无效的下标类型'list'

问题显然是,不是矩阵。什么是最有效的方式来解决这个问题?如果我想替换真实字符,也应该也可以。 BGSFDS与巴斯夫股票。

解决方案

一个不错的功能是 mapvalues() plyr包:

  require(plyr)
dataframe $ newdate< - mapvalues(dataframe
from = c(19921231,19931231,19941231),
to = c(1992,1993,1994))


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

解决方案

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

这篇关于根据规则将数据框中的值替换为其他值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆