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

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

Turn row values into variable labels

问题

Sure, here is the translated code part:

  1. 我有一个混乱的数据集,类似于这样:
  2. ```R
  3. Q1 <- "Age"
  4. Q2 <- "Sex"
  5. Q3 <- "Age"
  6. Q4 <- "Race"
  7. df <- data.frame(Q1, Q2, Q3, Q4)

如何将第一行的每个值转换为变量标签?
即:转换成类似这样的形式:

  1. library(labelled)
  2. var_label(df$Q1) <- "Age"
  3. var_label(df$Q2) <- "Sex"
  4. var_label(df$Q3) <- "Age"
  5. var_label(df$Q4) <- "Race"

我有一个包含许多变量的大型数据集。有没有更快更高效的方法来做这个?如何将第一行的每个值转换为变量标签?

我将不会回答关于翻译的问题。

  1. <details>
  2. <summary>英文:</summary>
  3. I have a messy dataset that is like this:

Q1 <- "Age"
Q2 <- "Sex"
Q3 <- "Age"
Q4 <- "Race"
df <- data.frame(Q1,Q2,Q3,Q4)

  1. [![enter image description here][1]][1]
  2. How do I turn every value of row 1 into variable label?
  3. 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"

  1. [![enter image description here][2]][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?
  3. I would appreciate all the help there is! Thanks!!!
  4. [1]: https://i.stack.imgur.com/CUPH6.png
  5. [2]: https://i.stack.imgur.com/YRAQW.png
  6. </details>
  7. # 答案1
  8. **得分**: 2
  9. The `var_label` 可以接受一个 `data.frame` 的向量作为输入,因此我们可以使用:
  10. ```R
  11. var_label(df) <- df[1, , drop = FALSE]

输出:

  1. > str(df)
  2. 'data.frame': 1 obs. of 4 variables:
  3. $ Q1: chr "Age"
  4. ..- attr(*, "label")= chr "Age"
  5. $ Q2: chr "Sex"
  6. ..- attr(*, "label")= chr "Sex"
  7. $ Q3: chr "Age"
  8. ..- attr(*, "label")= chr "Age"
  9. $ Q4: chr "Race"
  10. ..- attr(*, "label")= chr "Race"
英文:

The var_label can take a vector of data.frame as input, so, we can use

  1. var_label(df) &lt;- df[1, , drop = FALSE]

-output

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

答案2

得分: 0

你可以使用第一行作为变量标签,然后从数据框中删除第一行。

  1. var_label(df)=as.character(unlist(df[1,]))
  2. df=df[-1,]

希望有所帮助。

英文:

You can use the first row as the var label, and then drop the first from from the dataframe

  1. var_label(df)=as.character(unlist(df[1,]))
  2. 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:

确定