使用函数将R中的字符值转换为数值

使用函数将R中的字符值转换为数值,r,R,我希望加载并处理一个包含七个变量的CSV文件,一个是分组变量/因子(data$hashtag),六个是类别(data$support和其他),用“X”或“X”表示(或留空) 数据如何: recode <- function(x) { ifelse(x %in% c('X','x'), 1,0) } 重新编码怎么样: recode <- function(x) { ifelse(x %in% c('X','x'), 1,0) } 重新编码像这样的东西怎么样 # sample

我希望加载并处理一个包含七个变量的CSV文件,一个是分组变量/因子(
data$hashtag
),六个是类别(
data$support
和其他),用“X”或“X”表示(或留空)

数据如何:

recode <- function(x) {
  ifelse(x %in% c('X','x'), 1,0)
}
重新编码怎么样:

recode <- function(x) {
  ifelse(x %in% c('X','x'), 1,0)
}

重新编码像这样的东西怎么样

# sample data with support being a character vector
data.frame(support = c("X","X","0","x","0"),a=1:5,stringsAsFactors = F)->myDat
# convert to a factor and check the order of the levels
myDat$support <- as.factor(myDat$support)
levels(myDat$support)
#"0" "x" "X"
# just to see that it worked make an additional variable
myDat$supportrecoded <- myDat$support
# change levels and convert
levels(myDat$supportrecoded) <- c("0","1","1")
myDat$supportrecoded <- as.integer(as.character(myDat$supportrecoded ))
#支持为字符向量的样本数据
数据帧(支持=c(“X”、“X”、“0”、“X”、“0”),a=1:5,stringsAsFactors=F)->myDat
#转换为系数并检查标高的顺序

myDat$support像这样的东西怎么样

# sample data with support being a character vector
data.frame(support = c("X","X","0","x","0"),a=1:5,stringsAsFactors = F)->myDat
# convert to a factor and check the order of the levels
myDat$support <- as.factor(myDat$support)
levels(myDat$support)
#"0" "x" "X"
# just to see that it worked make an additional variable
myDat$supportrecoded <- myDat$support
# change levels and convert
levels(myDat$supportrecoded) <- c("0","1","1")
myDat$supportrecoded <- as.integer(as.character(myDat$supportrecoded ))
#支持为字符向量的样本数据
数据帧(支持=c(“X”、“X”、“0”、“X”、“0”),a=1:5,stringsAsFactors=F)->myDat
#转换为系数并检查标高的顺序

myDat$支持使用
plyr
中的
mapvalues

data$support <- as.numeric(mapvalues(data$support, c("X", "x", ""), c(1, 1, 0)))

使用
plyr
中的
mapvalues

data$support <- as.numeric(mapvalues(data$support, c("X", "x", ""), c(1, 1, 0)))

向量只能保存一种数据类型。因此,如果用数字变量替换字符串的一部分,它将转换为字符。您是如何在函数中使用
as.numeric()
的?
重新编码您可以尝试
return(as.numeric(x))
。正如我在之前的评论中所说,你这样做的方式仍然会迫使你转变为角色。或者你可以做
res向量只能保存一种数据类型。因此,如果用数字变量替换字符串的一部分,它将转换为字符。您是如何在函数中使用
as.numeric()
的?
重新编码您可以尝试
return(as.numeric(x))
。正如我在之前的评论中所说,你这样做的方式仍然会迫使你转变为角色。或者您可以执行
res以进一步练习,也可以使用
as.numeric()
将逻辑转换为0/1。因此,您可以执行
recode2,我将
添加为.integer(tolower(x)=“x”)
@docendodiscimus true,只需注意OP似乎需要数字。但是,bool似乎比int或float更符合逻辑:)为了进一步实践,您还可以使用
as.numeric()
将逻辑转换为0/1。因此,您可以执行
recode2,我将
添加为.integer(tolower(x)=“x”)
@docendodiscimus true,只需注意OP似乎需要数字。然而,bool似乎比int或float更符合逻辑:)