data.matrix()R语言中的函数用于通过将数据帧的所有值转换为数字模式然后将它们绑定为矩阵来创建矩阵。
用法: data.matrix(df)
参数:
df:要转换的数据帧。
范例1:
# R program to convert a data frame
# into a numeric matrix
# Creating a dataframe
df1 = data.frame(
"Name" = c("Amar", "Akbar", "Ronald"),
"Language" = c("R", "Python", "C#"),
"Age" = c(26, 38, 22)
)
# Printing data frame
print(df1)
# Converting into numeric matrix
df2 <- data.matrix(df1)
df2输出:
Name Language Age
1 Amar R 26
2 Akbar Python 38
3 Ronald C# 22
Name Language Age
[1, ] 2 3 26
[2, ] 1 2 38
[3, ] 3 1 22
范例2:
# R program to convert a data frame
# into a numeric matrix
# Creating a dataframe
df <- data.frame(sample(LETTERS[1:4], 8,
replace = T), cbind(1:4, 1:8))
colnames(df) <- c("x", "y", "z")
# Printing data frame
print(df)
# Converting into numeric matrix
df2 <- data.matrix(df)
df2输出:
x y z
1 A 1 1
2 D 2 2
3 C 3 3
4 A 4 4
5 B 1 5
6 B 2 6
7 A 3 7
8 C 4 8
x y z
[1, ] 1 1 1
[2, ] 4 2 2
[3, ] 3 3 3
[4, ] 1 4 4
[5, ] 2 1 5
[6, ] 2 2 6
[7, ] 1 3 7
[8, ] 3 4 8
相关用法
- R语言 melt()用法及代码示例
- R语言 is.numeric()用法及代码示例
- R语言 with()用法及代码示例
- R语言 as.matrix()用法及代码示例
- R Character Matrix转Numeric Matrix用法及代码示例
- R语言 expand.grid()用法及代码示例
- R语言 subset()用法及代码示例
- R语言 rename()用法及代码示例
- R语言 select()用法及代码示例
- R语言 mutate()用法及代码示例
- R语言 summarise()用法及代码示例
- R语言 sample_n()用法及代码示例
- R语言 as.character()用法及代码示例
- R语言 atanh()用法及代码示例
- R语言 asinh()用法及代码示例
- R语言 acosh()用法及代码示例
注:本文由纯净天空筛选整理自nidhi_biet大神的英文原创作品 Convert a Data Frame into a Numeric Matrix in R Programming – data.matrix() Function。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
