我是R
的新手,需要有关如何将字符值转换为数字的帮助。
我正在从CSV
文件中读取19个变量,它们包含以下值:
EXTREMELY IMPORTANT-10 ----> This should be actually value 10
9
8
and so on
NOT AT ALL IMPORTANT-01 ----> This should be actually value 01.
现在我需要将所有这19个变量的值从字符更改为数字 我写了以下代码,它给了我错误。
path <- "C:/Rajesh-Pandit/SPSS-Trial/BANKING/Salary-Account"
setwd(path)
library(foreign)
final_data <- read.csv("Rajhi-R.csv",header = TRUE, sep = ",")
str(final_data)
x <- (as.data.frame(final_data[,c(15:33)]))
summary(x)
y <- as.matrix(19)
importance <- as.matrix(19)
for(i in (1:19)){
if (x[i] == "EXTREMELY IMPORTANT-10") {y[i] <- 10}
else if (x[i] == "NOT AT ALL IMPORTANT-01") {y[i] <- 1}
else if (x[i] == "02") {y[i] <- 2}
else if (x[i] == "03") {y[i] <- 3}
else if (x[i] == "04") {y[i] <- 4}
else if (x[i] == "05") {y[i] <- 5}
else if (x[i] == "06") {y[i] <- 6}
else if (x[i] == "07") {y[i] <- 7}
else if (x[i] == "08") {y[i] <- 8}
else if (x[i] == "09") {y[i] <- 9}
}
y
importance <- y
基本上x[i]
个字符值不会更改为y[i]
。请给我反馈,说明为什么在这种情况下是否有效。
答案 0 :(得分:0)
你可以试试这个。
library('dplyr')
library('purrr')
library('magrittr')
# use map_if() if you want to round all numeric columns/vectors into 2 decimals
x %<>% mutate_each(funs(as.numeric)) %>% map_if(is.numeric, round, 2)