Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
97 views
in Technique[技术] by (71.8m points)

Column/Line in R

In R, i have a table where the column name is a date, how do I invert the columns by rows to be able to record in the database?

Example Table:

 estab  codigo               descricao 2021-02-01 2021-02-02
1    103 4390160                ANM 2003          0          0
2    103 4390161             ANM 2004 MF          0          0
3    103 4390162             ANM 2008 MF          0          0
4    103 4390193             ANM 3004 ST          0          0
5    103 4390189             ANM 3008 ST          0          0
6    103 4543512              ANM 24 NET          0          0
7    103 4390163             AMT 2008 RF          0          0
8    103 4543520    ANM 2003 COM BATERIA          0          0
9    103 4543521 ANM 2004 MF COM BATERIA          0          0
10   103 4543522 ANM 2008 MF COM BATERIA          0          0
11   103 4543523 ANM 3004 ST COM BATERIA          0          0
12   103 4543524 ANM 3008 ST COM BATERIA          0          0
13   103 4543516                AMT 8000          0          0
14   103 4390165                AMT 2018          0          0
15   103 4390164                AMT 2010          0          0

I tried to use melt, but it didn't work very well:

xxx <- reshape2::melt(xxx[[1]], id.vars = 'codigo')
question from:https://stackoverflow.com/questions/66068408/column-line-in-r

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If I understood your question, here is a code that should work for you:

# Tried recreating your dataframe
dt <- data.frame(estab = 103,
                 codigo = 4390160:4390174,
                 descricao = c("ANM 2003", "ANM 2004", "ANM BATERIA"),
                 "2021-02-01" = 0,
                 "2021-02-02" = 0)

dt <- reshape2::melt(dt, id.vars = c("estab", "codigo", "descricao"), variable.name = "Date", value.name = "Value")

# Make column into date
dt$Date <- gsub("X", "", dt$Date)
dt$Date <- as.Date(dt$Date, format = "%Y.%m.%d")

head(dt)

Screenshot of output


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...