0

I am trying to assign variable labels into my columns in R. I was able to create values list using the following code:

var.labels= dataframe$var name

now I want to use this list as variable labels for my columns in the data frame. I tried this code but it did not work:

label(dataframe) = as.list(var.labels[match(names(dataframe), names(var.labels))]

Thank you for your help.

  • It would be easier to help if you create a small reproducible example along with expected output. Read about [how to give a reproducible example](http://stackoverflow.com/questions/5963269). – Ronak Shah Feb 11 '21 at 05:21

1 Answers1

1

Maybe this?

var.labels <- dataframe$var name
colnames(dataframe) <- var.labels

Example:

df <- as.data.frame(replicate(n = 13, expr = sample(c(1:8, NA), 13, replace = TRUE)))
df$names <- LETTERS[1:13]
df
#>   V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13 names
#>1   1 NA  5  3  2  5  7 NA  3  NA  NA  NA   1     A
#>2   7  5  1  6  4  3  1  6  4   3  NA   3  NA     B
#>3   7  3  1  2  7  2  6  4  6   1   7   3   2     C
#>4   3  1  5  1  5  6  1  2  2  NA   8   5   1     D
#>5   3  6  3  7  4  2  6  7  7  NA   1   2   8     E
#>6  NA  4  4  1  8  3  8 NA  6   3   8   4  NA     F
#>7   1  8  3  8  1  3  2  4  7   4   2   1   2     G
#>8  NA NA  2  3  5  4  5  1  4   7   8   5   3     H
#>9   7 NA  3  2  7 NA  2  8  7  NA   6   8   6     I
#>10  6  8  5  3  6  5  5  3  4   8  NA   5   1     J
#>11  1  7  8  5  1  2  3 NA NA   3   2   6   7     K
#>12  8  4  1  8  7 NA  6  6  5   6   7  NA   2     L
#>13  5  8  5  1  2  1  6  3 NA   1   7   3   5     M

colnames(df) <- df$names
#>    A  B C D E  F G  H  I  J  K  L  M NA
#>1   1 NA 5 3 2  5 7 NA  3 NA NA NA  1  A
#>2   7  5 1 6 4  3 1  6  4  3 NA  3 NA  B
#>3   7  3 1 2 7  2 6  4  6  1  7  3  2  C
#>4   3  1 5 1 5  6 1  2  2 NA  8  5  1  D
#>5   3  6 3 7 4  2 6  7  7 NA  1  2  8  E
#>6  NA  4 4 1 8  3 8 NA  6  3  8  4 NA  F
#>7   1  8 3 8 1  3 2  4  7  4  2  1  2  G
#>8  NA NA 2 3 5  4 5  1  4  7  8  5  3  H
#>9   7 NA 3 2 7 NA 2  8  7 NA  6  8  6  I
#>10  6  8 5 3 6  5 5  3  4  8 NA  5  1  J
#>11  1  7 8 5 1  2 3 NA NA  3  2  6  7  K
#>12  8  4 1 8 7 NA 6  6  5  6  7 NA  2  L
#>13  5  8 5 1 2  1 6  3 NA  1  7  3  5  M

# Finally, remove the names column
df[14] <- NULL
jared_mamrot
  • 22,354
  • 4
  • 21
  • 46