英文:
Turn row values into variable labels
问题
Sure, here is the translated code part:
我有一个混乱的数据集,类似于这样:
```R
Q1 <- "Age"
Q2 <- "Sex"
Q3 <- "Age"
Q4 <- "Race"
df <- data.frame(Q1, Q2, Q3, Q4)
如何将第一行的每个值转换为变量标签?
即:转换成类似这样的形式:
library(labelled)
var_label(df$Q1) <- "Age"
var_label(df$Q2) <- "Sex"
var_label(df$Q3) <- "Age"
var_label(df$Q4) <- "Race"
我有一个包含许多变量的大型数据集。有没有更快更高效的方法来做这个?如何将第一行的每个值转换为变量标签?
我将不会回答关于翻译的问题。
<details>
<summary>英文:</summary>
I have a messy dataset that is like this:
Q1 <- "Age"
Q2 <- "Sex"
Q3 <- "Age"
Q4 <- "Race"
df <- data.frame(Q1,Q2,Q3,Q4)
[![enter image description here][1]][1]
How do I turn every value of row 1 into variable label?
i.e: into something like this:
library(labelled)
var_label(df$Q1) <- "Age"
var_label(df$Q2) <- "Sex"
var_label(df$Q3) <- "Age"
var_label(df$Q4) <- "Race"
[![enter image description here][2]][2]
I have a large dataset with many variables. Is there a faster and efficient way to do this? How do I turn every value of row 1 into variable label?
I would appreciate all the help there is! Thanks!!!
[1]: https://i.stack.imgur.com/CUPH6.png
[2]: https://i.stack.imgur.com/YRAQW.png
</details>
# 答案1
**得分**: 2
The `var_label` 可以接受一个 `data.frame` 的向量作为输入,因此我们可以使用:
```R
var_label(df) <- df[1, , drop = FALSE]
输出:
> str(df)
'data.frame': 1 obs. of 4 variables:
$ Q1: chr "Age"
..- attr(*, "label")= chr "Age"
$ Q2: chr "Sex"
..- attr(*, "label")= chr "Sex"
$ Q3: chr "Age"
..- attr(*, "label")= chr "Age"
$ Q4: chr "Race"
..- attr(*, "label")= chr "Race"
英文:
The var_label
can take a vector of data.frame
as input, so, we can use
var_label(df) <- df[1, , drop = FALSE]
-output
> str(df)
'data.frame': 1 obs. of 4 variables:
$ Q1: chr "Age"
..- attr(*, "label")= chr "Age"
$ Q2: chr "Sex"
..- attr(*, "label")= chr "Sex"
$ Q3: chr "Age"
..- attr(*, "label")= chr "Age"
$ Q4: chr "Race"
..- attr(*, "label")= chr "Race"
答案2
得分: 0
你可以使用第一行作为变量标签,然后从数据框中删除第一行。
var_label(df)=as.character(unlist(df[1,]))
df=df[-1,]
希望有所帮助。
英文:
You can use the first row as the var label, and then drop the first from from the dataframe
var_label(df)=as.character(unlist(df[1,]))
df=df[-1,]
hope it helps
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论