我想将数据框转换为我的
df
df <- read.csv("https://raw.githubusercontent.com/Leprechault/trash/refs/heads/main/Dados_C3_data_planta.csv", sep=";")
head(df)
# Data GLY_PN CRO_P MIPU_P CEN_P POA01_P CECRO_P COM_P MOR_PN
#1 24-01-2024 53 40 3 0 0 0 0 0
#2 25-01-2024 56 8 0 24 9 0 0 0
#3 26-01-2024 0 27 0 47 26 0 0 0
#4 27-01-2024 0 0 0 0 0 6 43 48
#5 31-01-2024 0 0 0 62 35 0 0 0
#6 02-02-2024 0 0 0 50 50 0 0 0
# COPA_PN RHY_P SOR_P
#1 0 0 0
#2 0 0 0
#3 0 0 0
#4 0 0 0
#5 0 0 0
#6 0 0 0
去上课
[1] "matrix" "array"
。我无法将其与 as.matrix()
或 data.matrix()
一起使用。
期望的输出(~
df_to_matrix
):
# GLY_PN CRO_P MIPU_P CEN_P POA01_P CECRO_P COM_P MOR_PN
#1 24-01-2024 53 40 3 0 0 0 0 0
#2 25-01-2024 56 8 0 24 9 0 0 0
#3 26-01-2024 0 27 0 47 26 0 0 0
#4 27-01-2024 0 0 0 0 0 6 43 48
#5 31-01-2024 0 0 0 62 35 0 0 0
#6 02-02-2024 0 0 0 50 50 0 0 0
# COPA_PN RHY_P SOR_P
#1 0 0 0
#2 0 0 0
#3 0 0 0
#4 0 0 0
#5 0 0 0
#6 0 0 0
class(df_to_matrix)
[1] "matrix" "array"
第一列中的列名称和数字格式的值。
# Load the data
df <- read.csv("https://raw.githubusercontent.com/Leprechault/trash/refs/heads/main/Dados_C3_data_planta.csv", sep=";")
# Convert to matrix, excluding the first column (dates)
df_to_matrix <- as.matrix(df[, -1]) # Exclude the first column
# Optionally, convert character columns to numeric
df_to_matrix <- apply(df_to_matrix, 2, as.numeric)
# Check the class
class(df_to_matrix)
# Print the resulting matrix
print(df_to_matrix)
将数据框转换为zoo,然后转换为矩阵。
library(zoo)
df |> read.zoo(format = "%d-%m-%Y") |> as.matrix()
为该矩阵提供从第一列构造的行名称,标准化为使用 yyyy-mm-dd 格式,与原始格式不同,按日期顺序排序。
GLY_PN CRO_P MIPU_P CEN_P POA01_P CECRO_P COM_P MOR_PN COPA_PN RHY_P SOR_P
2024-01-24 53 40 3 0 0 0 0 0 0 0 0
2024-01-25 56 8 0 24 9 0 0 0 0 0 0
2024-01-26 0 27 0 47 26 0 0 0 0 0 0
2024-01-27 0 0 0 0 0 6 43 48 0 0 0
2024-01-31 0 0 0 62 35 0 0 0 0 0 0
2024-02-02 0 0 0 50 50 0 0 0 0 0 0
2024-02-05 0 0 0 0 0 0 0 0 99 0 0
2024-02-06 0 0 81 0 0 0 0 0 0 17 0
2024-02-07 0 0 0 58 10 0 0 0 0 0 33
2024-02-09 0 0 0 0 0 0 0 0 0 32 64
2024-02-10 0 0 0 47 22 0 0 0 0 0 64
我们可以将
as.matrix()
与 `row.names<-`()
一起使用。
`row.names<-`(as.matrix(d0[-1]), d0[[1]])
GLY_PN CRO_P MIPU_P CEN_P POA01_P CECRO_P COM_P MOR_PN COPA_PN RHY_P SOR_P
24-01-2024 53 40 3 0 0 0 0 0 0 0 0
25-01-2024 56 8 0 24 9 0 0 0 0 0 0
26-01-2024 0 27 0 47 26 0 0 0 0 0 0
27-01-2024 0 0 0 0 0 6 43 48 0 0 0
31-01-2024 0 0 0 62 35 0 0 0 0 0 0
02-02-2024 0 0 0 50 50 0 0 0 0 0 0
05-02-2024 0 0 0 0 0 0 0 0 99 0 0
06-02-2024 0 0 81 0 0 0 0 0 0 17 0
07-02-2024 0 0 0 58 10 0 0 0 0 0 33
09-02-2024 0 0 0 0 0 0 0 0 0 32 64
10-02-2024 0 0 0 47 22 0 0 0 0 0 64
无外部封装。
数据。
d0 = read.csv("https://raw.githubusercontent.com/Leprechault/trash/refs/heads/main/Dados_C3_data_planta.csv", sep=";")