R 在几列中重新编码一些值,并保留这些列中的所有其他内容不变
在我的data.frameR 在几列中重新编码一些值,并保留这些列中的所有其他内容不变,r,dataframe,if-statement,dplyr,tidyverse,R,Dataframe,If Statement,Dplyr,Tidyverse,在我的data.framed2中,我试图重新编码几列中的一些值,并保留这些列中的所有其他内容。具体来说,我想做以下工作: profic:将77s替换为99s; cf.type:将15s替换为99s; 长度:将0s替换为1s,将3s替换为2s; 分级:将88s替换为99s 我尝试了以下方法,但似乎没有得到想要的结果(即,重新编码列中的其他值被删除),是否对此进行了修复 library(tidyverse) d2 <- read.csv('https://raw.githubusercont
d2
中,我试图重新编码几列中的一些值,并保留这些列中的所有其他内容。具体来说,我想做以下工作:
profic
:将77s替换为99s;
cf.type
:将15s替换为99s;
长度
:将0s替换为1s,将3s替换为2s;
分级
:将88s替换为99s
我尝试了以下方法,但似乎没有得到想要的结果(即,重新编码列中的其他值被删除),是否对此进行了修复
library(tidyverse)
d2 <- read.csv('https://raw.githubusercontent.com/rnorouzian/m/master/v13.csv')
d3 <- mutate(d2, profic = recode(profic, "77"="99"),
cf.type = recode(cf.type, "15"="99"),
Length = recode(Length, "0"="1", "3"="2"),
graded = recode(graded, "88"="99")
)
库(tidyverse)
d2要替换数值,请使用:
library(dplyr)
d3 <- mutate(d2, profic = recode(profic, `77` = 99L),
cf.type = recode(cf.type, `15` = 99L),
Length = recode(Length, `0` =1L, `3`= 2L),
graded = recode(graded, `88`= 99L))
库(dplyr)
d3recode对于变量类型非常特殊。运行代码时收到的消息是警告消息:被视为NA as.x的未替换值不兼容。请详细指定替换或供应。默认值
。
如果运行scape(d2)
您将看到profic
、cf.type
、Length
和grade
都是int
(整数)。您可以通过在末尾添加一个L(如so9L
)来指定数字是R中的整数。比较str(9)
和str(9L)
,第一个是数字,第二个是整数
您还需要仅删除RHS上的引号-如果将替换值保留为引号,它们将被解释为字符串文字而不是数字。如果删除LHS上的引号,将出现不同的错误,这超出了本答案的范围
d2 <- read.csv('https://raw.githubusercontent.com/rnorouzian/m/master/v13.csv')
d3 <- mutate(d2, profic = recode(profic, "77"=99L),
cf.type = recode(cf.type, "15"=99L),
Length = recode(Length, "0"=1L, "3"=2L),
graded = recode(graded, "88"=99L)
)
d2