CSV文件中的输入数据如下所示:
Input:
1 1 a x
1 2 b y
1 3 c z
2 1 d u
2 2 e t
2 3 f j
3 1 g g
3 2 h f
3 3 i v
我使用write.csv命令将CSV文件操作为带有输出的矩阵。这是我的代码:
plid <- read.csv("random.csv")
table1 = dcast(plid, V1 ~ V2, value.var = "V3")
table2 = dcast(plid, V1 ~ V2, value.var = "V4")
write.csv(table1, "test1.csv", row.names = FALSE)
write.csv(table2, "test2.csv", row.names = FALSE)
输出如下:(注意:字母实际上是整数,在这种情况下仅用于简单。所以这里它使用输入CSV文件的前3列。
1 2 3
1 a b c
2 d e f
3 g h i
同样,使用前2列和第4列,输出如下所示:
1 2 3
1 x y z
2 u t j
3 g f v
最后,我想通过对两个矩阵中的填充数据进行求和,将这两个新编写的CSV合并为一个。输出(或table3)应如下所示:
1 2 3
1 a+x b+y c+z
2 d+u e+t f+j
3 g+g h+f v+i
我希望保持第一行和第一列编号固定(在table1和table2中),矩阵(table1)中的填充数据将在(table2)中添加数字以创建table3。
我尝试了以下内容:
table3=table1[-1,-1] + table2[-1,-1]
write.csv(table3, "test3.csv", row.names=FALSE
它有效,但它会删除第一列1,2,3,4 ......,原因我不太确定。
有什么方法可以解决这个问题吗?
答案 0 :(得分:1)
不清楚初始文件/所需输出是什么样的,但如果你正在使用数字,可以通过对行进行求和然后转换为矩阵来完成吗?
如果df
是您的初始表:
# Recreate your table, but with numbers
df <- data.frame(columnName1 = rep(1:3,3), columnName2 = sample(1:100,9), columnName3 = sample(1:100,9))
# Sum all rows together except first column
row_sum_vector <- rowSums(df[,2:ncol(df)])
# Convert to 3 by 3 matrix
df_final <- matrix(row_sum_vector, nrow = 3)
答案 1 :(得分:0)
mat1 <- matrix(c("a","b","c","d","e","f","g","h","i"), nrow=3,byrow=TRUE)
mat2 <- matrix(c("x","y","z","u","t","j","g","f","v"), nrow=3,byrow=TRUE)
mat1
# [,1] [,2] [,3]
#[1,] "a" "b" "c"
#[2,] "d" "e" "f"
#[3,] "g" "h" "i"
mat2
# [,1] [,2] [,3]
#[1,] "x" "y" "z"
#[2,] "u" "t" "j"
#[3,] "g" "f" "v"
matrix(paste(mat1, mat2, sep = "+"), nrow = 3)
# [,1] [,2] [,3]
#[1,] "a+x" "b+y" "c+z"
#[2,] "d+u" "e+t" "f+j"
#[3,] "g+g" "h+f" "i+v"