将行数值转化为变量标签。

huangapple go评论93阅读模式
英文:

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) &lt;- df[1, , drop = FALSE]

-output

&gt; str(df)
&#39;data.frame&#39;:	1 obs. of  4 variables:
 $ Q1: chr &quot;Age&quot;
  ..- attr(*, &quot;label&quot;)= chr &quot;Age&quot;
 $ Q2: chr &quot;Sex&quot;
  ..- attr(*, &quot;label&quot;)= chr &quot;Sex&quot;
 $ Q3: chr &quot;Age&quot;
  ..- attr(*, &quot;label&quot;)= chr &quot;Age&quot;
 $ Q4: chr &quot;Race&quot;
  ..- attr(*, &quot;label&quot;)= chr &quot;Race&quot;

答案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

huangapple
  • 本文由 发表于 2023年4月13日 21:19:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76005926.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定