我有一维数据框作为输入:
A,1,B,2,C,3,D,4
我需要转换为这样的2D数据框:
A,1
B,2
C,3
D,4
我该怎么做?我无法使用matrix(...)
,因为数据框包含非数字值。
根据要求[编辑] dput
数据:
structure(list(V1 = structure(1L, .Label = "A", class = "factor"),
V2 = 1, V3 = structure(1L, .Label = "B", class = "factor"),
V4 = 2, V5 = structure(1L, .Label = "C", class = "factor"),
V6 = 3, V7 = structure(1L, .Label = "D", class = "factor"),
V8 = 4), .Names = c("V1", "V2", "V3", "V4", "V5", "V6",
"V7", "V8"), class = "data.frame", row.names = c(NA, -1L))
答案 0 :(得分:2)
您可以使用沿列回收的逻辑向量来对1D数据帧中的列进行子集化。
data.frame(x = unlist(d[ , c(TRUE, FALSE)]), y = unlist(d[ , c(FALSE, TRUE)]))
# x y
# V1 A 1
# V3 B 2
# V5 C 3
# V7 D 4
答案 1 :(得分:0)
matrix
函数参数byrow
在这里有帮助。然后你可以改变课程
data <- data.frame(matrix(c("A",1,"B",2,"C",3,"D",4),ncol=2,byrow=T))
class(data$X1) <- "numeric"
sapply(data,class)
X1 X2
"integer" "factor"
答案 2 :(得分:0)
> matrix( sapply(dat,as.character), 4, byrow=TRUE)
[,1] [,2]
[1,] "A" "1"
[2,] "B" "2"
[3,] "C" "3"
[4,] "D" "4"
如果我们可以假设&#34; n&#34;作为列号的请求是一个值的数值因子:
> matrix( sapply(dat,as.character), length(dat)/2, byrow=TRUE)
[,1] [,2]
[1,] "A" "1"
[2,] "B" "2"
[3,] "C" "3"
[4,] "D" "4"
显然,如果第二列需要为数字类,则需要将其强制转换为数据框,但是问题描述中没有任何内容表明应该是这样的。