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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
