這是我的代碼:
# reading input file
library(readxl)
df_testing <- read_excel("Testing_Data.xlsx")
# Renaming the 1st column name for ease of use
colnames(df_testing)[1] = "Tag_No"
View(df_testing)
# creating a new data frame with columns from the row values
library(tidyr)
df_output = pivot_wider(df_testing, names_from = Tag_No, values_from = Reading)
# the below output is as expected, yet coming in list cols
View(df_output)
# this below code is an attempt to fix but replaces last row values with NA
# df_output = lapply(df_output, unlist)
# df_output = data.frame(lapply(df_output, `length<-`, max(lengths(df_output))))
# level count should be equal to no of columns created
length(levels(df_testing$Tag_No)) == ncol(df_output) - 3
# save output to the file. Since, it is in list cols, I can't save the data to the file
write.csv(df_output, file = "Output File.csv")
這是輸入資料 檔案鏈接 1
這是預期輸出資料檔案鏈接 2的示例
歡迎任何更改代碼以使其正常作業而不會丟失資料或完整的解決方案。提前致謝。如果我誤解了 pivot_wider 用法的概念,請提供一些提示。
uj5u.com熱心網友回復:
問題出在NA價值觀上。其中大約有 59 行NA。
library(readxl)
library(tidyr)
df_testing <- read_excel("Testing_Data.xlsx")
df_testing %>% filter(is.na(`Tag No.`))
# A tibble: 59 x 4
# `Tag No.` Reading Date Time
# <chr> <dbl> <dttm> <dttm>
# 1 NA NA NA NA
# 2 NA NA NA NA
# 3 NA NA NA NA
# 4 NA NA NA NA
# 5 NA NA NA NA
# 6 NA NA NA NA
# 7 NA NA NA NA
# 8 NA NA NA NA
# 9 NA NA NA NA
#10 NA NA NA NA
# … with 49 more rows
洗掉NA行不會給出串列列。
df_output <- pivot_wider(na.omit(df_testing), names_from = `Tag No.`, values_from = Reading)
df_output
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/397786.html
下一篇:R中的掩碼電話號碼
