我的数据框架结构如下:
'data.frame': 74 obs. of 7 variables:
$ Scientific_Name : Factor w/ 74 levels "Aesculus glabra",..: 1 2 3 4 5 6 7 8 9 10 ...
$ Endangered.or.threatened : int 0 0 1 0 1 1 0 1 1 0 ...
$ Lat_spread : num 12.95 1.22 13.18 11.23 15.74 ...
$ Restricted_range : int 0 0 0 1 0 1 0 1 0 0 ...
$ Available : int 1 1 0 1 1 0 0 0 0 1 ...
$ Abiotic_adapted_not_including_availability: int 4 NA 3 3 4 3 4 4 4 4 ...
$ Dispersal_score : int 5 NA 2 2 9 2 4 1 5 4 ...
我正在尝试将整数列转换为数字向量。这是我的代码:
> RestrictedY <- subset(Status_restricted_Wilcox, Endangered.or.threatened == 1, select = Restricted_range)
> RestrictedY <- as.vector(RestrictedY)
> RestrictedY <- as.numeric(RestrictedY)
Error: (list) object cannot be coerced to type 'double'
> Status_restricted_Wilcox <- read.csv("~/Documents/Honours_data_analysis/Status_restricted_Wilcox.csv", na.strings="NA_integer_")
> View(Status_restricted_Wilcox)
> RestrictedY <- subset(Status_restricted_Wilcox, Endangered.or.threatened == 1, select = Restricted_range)
> RestrictedY <- as.vector(RestrictedY)
> RestrictedY <- as.numeric(RestrictedY)
Error: (list) object cannot be coerced to type 'double'
我做错了什么?我的错误是“双重”,但我不明白这是什么问题。 谢谢!
答案 0 :(得分:0)
当您使用subset()
时,您将始终获得data.frame,这与使用其他形式的子集时不同,后者在您选择单个列时返回向量。您不能将data.frame强制转换为原子数值。尝试
RestrictedY <- subset(Status_restricted_Wilcox, Endangered.or.threatened == 1, select = Restricted_range)[[1]]
#or
RestrictedY <- subset(Status_restricted_Wilcox, Endangered.or.threatened == 1)$Restricted_range)
# or
RestrictedY <- with(Status_restricted_Wilcox, Restricted_range[Endangered.or.threatened == 1])
你不需要任何进一步的强制,因为R通常很擅长在必要时将整数转换为数字。