我需要将来自单个多维列表上的两个命名列的一些数据转换为具有两列的单个列表,并且结果中每行中的数据需要来自源列表中的匹配行。请参阅以下伪代码:
object <- data.frame()
object$Property1 <- c('a', 'b', 'c')
object$Property2 <- c(1, 2, 3)
object$Property3 <- c('X', 'Y', 'Z')
object$Property4 <- c('other', 'data', 'here')
result = matrix(NA, nrow=length(object), ncol=2)
# This is what I need help with
result$Property1 <- object$Property1
result$Property2 <- object$Property2
在上面的代码运行之后,result
变量应该有这样的值:
row | result$Property1 | result$Property2 | 1 | 'a' | 1 | 2
---|---|---|
'b' | 2 | |
3'c' | 3 |
构造data.frame的方法是创建向量(如果需要),然后在data.frame
中传递它们。在OP的代码中,data.frame
被创建为0行,0列,当我们使用$
添加列时,它会失败。
Property1 <- c('a', 'b', 'c')
Property2 <- c(1, 2, 3)
Property3 <- c('X', 'Y', 'Z')
Property4 <- c('other', 'data', 'here')
object <- data.frame(Property1, Property2, Property3, Property4)
-ouptut
> object
Property1 Property2 Property3 Property4
1 a 1 X other
2 b 2 Y data
3 c 3 Z here
对于akrun的数据:我们也可以使用tibble
:见这里:
Property1 <- c('a', 'b', 'c')
Property2 <- c(1, 2, 3)
Property3 <- c('X', 'Y', 'Z')
Property4 <- c('other', 'data', 'here')
library(tibble)
object <- tibble(Property1, Property2, Property3, Property4)
输出:
# A tibble: 3 x 4
Property1 Property2 Property3 Property4
<chr> <dbl> <chr> <chr>
1 a 1 X other
2 b 2 Y data
3 c 3 Z here