在这里,我们将解释如何编写R程序以从给定数据框中选择一些随机行。这里我们使用内置函数 data.frame(), nrow()。数据框用于存储数据表,它包含长度相等的向量列表。数据框通过函数 data.frame() 创建,它包含紧密耦合的变量集合。而方法 nrow() 返回 x 中存在的行数。该函数的语法是,
nrow(x)
其中 x 表示向量、数组、数据框或NULL。
以下是R程序中用于更改给定数据框列名的步骤。在此R程序中,我们直接将数据框传递给内置函数。这里我们使用变量 E, N, S, A, Q 来保存不同类型的向量。调用函数 data.frame() 来创建 数据框。最后,通过调用方法 nrow() 来选择随机行,例如 E[sample(nrow(E), 3),]
步骤1:使用向量值为变量E、N、S、A、Q赋值
步骤2:首先打印原始向量值
步骤3:通过调用 E[sample(nrow(E), 3),] 选择随机行
步骤4:打印最终的数据框
E = data.frame(
N = c('Jhon', 'Hialy', 'Albert', 'James', 'Delma'),
S = c(10, 9.5, 12.2, 11, 8),
A = c(2, 1, 2, 4, 1),
Q = c('yes', 'no', 'yes', 'no', 'no')
)
print("Original data frame:")
print(E)
print("Select three random rows of the data frame:")
print(E[sample(nrow(E), 3),])
[1] "Original data frame:"
N S A Q
1 Jhon 10.0 2 yes
2 Hialy 9.5 1 no
3 Albert 12.2 2 yes
4 James 11.0 4 no
5 Delma 8.0 1 no
[1] "Select three random rows of the data frame:"
N S A Q
4 James 11.0 4 no
5 Delma 8.0 1 no
3 Albert 12.2 2 yes