Skip to content
Prev 395370 / 398502 Next

How to Reformat a dataframe

?s 04:13 de 28/10/2023, Paul Bernal escreveu:
Hello,

Here are two base R way with ?stack and with ?reshape.


# 1. With stack()
df_long <- stack(alajuela_df)[1]
df_long <- df_long[complete.cases(df_long), , drop = FALSE]
head(df_long)



# 2. With reshape
df_long <- reshape(
   alajuela_df, direction = "long",
   varying = names(alajuela_df),
   v.names = "x"
)[2]

# 1512 rows, only one column
dim(df_long)
# [1] 1512    1

# there are NA's in the data
df_long[complete.cases(df_long), , drop = FALSE] |> dim()
# [1] 1509    1

# keep the rows with values not NA
df_long <- df_long[complete.cases(df_long), , drop = FALSE]

# check the dimensions again
dim(df_long)
# [1] 1509    1



Hope this helps,

Rui Barradas