我想创建一个数据框“Coefficients”。首先,我从另一个数据框“APD”中提取一列:
str(APD.frame <- read.table("APD_data_15.txt", header = TRUE, sep = "", dec = "."))
APD.frame <- within(APD.frame, {
Serial_number <- factor(Serial_number)
Lot <- factor(Lot)
Wafer <- factor(Wafer)} )
Coefficients<- data.frame(APD["Serial_number"])
现在我想添加一些通配符列(使我更容易理解以下过程):
Coefficients[2]<- c(1)
Coefficients[3]<- 1
Coefficients[4]<- NA
在所有情况下,我都会收到“未知列”(通过鼠标翻转显示在RStudio中)。我需要它们是数字的。为什么我无法将它们转换为数字的:Coefficients[3]<- as.numeric(Coefficients[3])
如何确保列为数字/为什么它们不是?
最小例子:http://www.datafilehost.com/d/5d00de23
> class(Coefficients[2])
[1] "data.frame"
> Coefficients<- transform(Coefficients, Coefficients[2] = as.numeric(Coefficients[2]))
Error: unexpected '=' in "Coefficients<- transform(Coefficients, Coefficients[2] ="
答案 0 :(得分:1)
您的问题是重复的,但是,这里的答案的简短版本基于此问题的详细答案How to convert a data frame column to numeric type?:
df <- data.frame(X = c("1","2","3")
,Y =c("3","4","5")
)
sum(df$X) # you`ll get an error
class(df$X)
df <- transform(df, X = as.numeric(df$X))
sum(df$X) # no more error, due to conversion to numeric
class(df$X)
#Update
#after discussion in chat the following lines helped
#convert all columns of data.frame to certain type, here numeric
df[] <- lapply(df, as.numeric)
#convert an individual column, to a certain type, here numeric
#check ?transform for accepted types for conversion
#df would be Coefficients in your example,
#column name would be Serial_Number
df$columnname <- transform(df, columnname = as.numeric(df$columnname))