Infection 1 Infection 2 Infection 3
6 10 0
10 0 0
0 0 0
3 5 0
10 10 1
我有一个放入R的csv文件,我想创建一个仅指示非零单元格的布尔向量。
答案 0 :(得分:1)
我猜你的意思是vector
你的意思是你提供的matrix
。 (为了将来参考,vector
只有一个维度。它是list
值的一种形式。matrix
(或data.frame
或data.table
)有2个(或更多)尺寸,如X行* Y列)。如果我猜错了,请用您想要的输出格式更新您的问题。
指示哪些数字不为零的简单方法是在矩阵上使用标准比较:
# Recreate your table for this example:
infection_vals <- data.frame(c(6,10,0,3,10), c(10,0,0,5,10), c(0,0,0,0,1));
# You have column names with spaces which can be tricky in R
colnames(infection_vals) <- c("Infection 1", "Infection 2", "Infection 3");
# Output to see it
infection_vals;
> Infection 1 Infection 2 Infection 3
>1 6 10 0
>2 10 0 0
>3 0 0 0
>4 3 5 0
>5 10 10 1
# It's easier than you think. Just do a comparison on the table and R will
# iterate through each cell automatically and return a matrix of the same dimensions:
boolean_infection_vals <- (infection_vals > 0 | infection_vals <0);
boolean_infection_vals;
> Infection 1 Infection 2 Infection 3
>[1,] TRUE TRUE FALSE
>[2,] TRUE FALSE FALSE
>[3,] FALSE FALSE FALSE
>[4,] TRUE TRUE FALSE
>[5,] TRUE TRUE TRUE
# Check the type and class of the result
typeof(boolean_infection_vals);
>[1] "logical"
class(boolean_infection_vals);
>[1] "matrix"
# If we convert the matrix to a data.frame, we can more easily work with the columns
boolean_infection_vals_df <- as.data.frame(boolean_infection_vals);
# You can access each column of the data.frame as a vector with the $ operator.
# Quotes are needed because you have spaces in the column names
boolean_infection_vals_df$"Infection 1";
>[1] TRUE TRUE FALSE TRUE TRUE
祝你好运! :)