R语言 计算R数据框架中每一列的非零值
在这篇文章中,我们将使用R编程语言来计算数据中的非零数据项的数量。
要检查数据中的非零数据项的数量,首先我们必须使用 以下方法 将数据放入数据框中 。
data <- data.frame(x1 = c(1,2,0,100,0,3,10),
x2 = c(5,0,1,8,10,0,0),
x3 = 0)
print(data)
输出:
现在我们有了数据框中的数据。因此,为了计算每一列中非零条目的数量,我们使用colSums()函数。这个函数的使用方法是。
colSums( data != 0)
输出:
你可以清楚地看到,数据框中有3列,Col1有5个非零条目(1,2,100,3,10),Col2有4个非零条目(5,1,8,10),Col3有0个非零条目。
例1: 这里我们要创建一个数据框架,然后计算每一列的非零值。
# Create example data frame
data <- data.frame(x1 = c(1,2,0,100,0,3,10),
x2 = c(5,0,1,8,10,0,0),
x3 = 0)
# print the dataframe
print(data)
# check for every non zero entry using "data!=0"
# and sum the number of entries using colSums()
colSums(data != 0)
输出:
例2: 在这个例子中,我们使用的是iris3数据集。
# put the iris3 data in dataframe
data <- data.frame(iris3)
# check the dimensions of dataframe
dim(data)
# check for every non zero entry using "data!=0"
# and sum the number of entries using colSums()
colSums(data != 0)
输出:
例3: 在这个例子中,使用了state.x77数据集。
# put the state.x77 data in dataframe
data <- data.frame(state.x77)
# check the dimensions of dataframe
dim(data)
# check for every non zero entry using "data!=0"
# and sum the number of entries using colSums()
colSums(data != 0)
输出:
例子4: 在这个例子中,使用了USArrest数据集。
# put the USArrest data in dataframe
data <- data.frame(USArrest)
# check the dimensions of dataframe
dim(data)
# check for every non zero entry using "data!=0"
# and sum the number of entries using colSums()
colSums(data != 0)
输出: