如何将因子转换为数值

时间:2018-09-10 10:54:29

标签: r ggplot2

我的数据:

data <- read.table(text = "Component    Method  Average StdErr
N170    Image   0,58904 0,0066948
P300    Image   0,84932 0,0048678
Sham    Image   0,23944 0,0058078
N170    Topo    0,64384 0,0065159
P300    Topo    0,90278 0,0040316
Sham    Topo    0,32877 0,0063921
N170    Joint   0,65278 0,0064788
P300    Joint   0,84722 0,0048959
Sham    Joint   0,26230 0,0059937", header = TRUE)

我想使用ggplot2进行绘制。尝试计算误差线时,出现错误。我发现这是因为“平均”是一个因素,而不是数字。运行我的代码:

ggplot(data=data, aes(x=Method, y=Average, group=Component)) + 
  geom_line(aes(colour=Component), size=1)+
  geom_pointrange(aes(ymin=Average-StdErr, ymax=Average+StdErr))+
  geom_point(aes(colour=Component), size=3)+
  theme_classic()

给我这个错误信息:

Warning messages:
1: In Ops.factor(Average, StdErr) : ‘-’ not meaningful for factors
2: In Ops.factor(Average, StdErr) : ‘+’ not meaningful for factors
3: Removed 9 rows containing missing values (geom_pointrange).

我曾尝试使用此代码将Average和StdErr转换为数字,但是并不能解决我的问题。

data$Average <- as.numeric(data$Average)
data$StdErr <- as.numeric(as.vector(data$StdErr))

或者,我尝试以.csv格式读取数据:

data <- read.csv(file="C:/Users/XXX/Desktop/XXX/XX/ggplot/corrComp_agg.csv", 
                 header=TRUE, sep=",")

但是收到一条错误消息:

Error in read.table(file = file, header = header, sep = sep, quote = quote,  : 
  more columns than column names

我想念什么?

1 个答案:

答案 0 :(得分:2)

您应该将逗号读为十进制字符。.在dec = ","语句中使用read.table

data <- read.table(text = "Component    Method  Average StdErr
N170    Image   0,58904 0,0066948
                   P300    Image   0,84932 0,0048678
                   Sham    Image   0,23944 0,0058078
                   N170    Topo    0,64384 0,0065159
                   P300    Topo    0,90278 0,0040316
                   Sham    Topo    0,32877 0,0063921
                   N170    Joint   0,65278 0,0064788
                   P300    Joint   0,84722 0,0048959
                   Sham    Joint   0,26230 0,0059937", dec =",", header = TRUE)

现在您的AverageStdErr是数字

sapply(data, class)
#Component    Method   Average    StdErr 
# "factor"  "factor" "numeric" "numeric" 

所以,现在绘制很容易

ggplot(data=data, aes(x=Method, y=Average, group=Component)) + 
  geom_line(aes(colour=Component), size=1)+
  geom_pointrange(aes(ymin=Average-StdErr, ymax=Average+StdErr))+
  geom_point(aes(colour=Component), size=3)+
  theme_classic()

enter image description here