使用 r 将两个变量的值组合在一起以创建一个新变量

编程入门 行业动态 更新时间:2024-10-25 13:30:47
本文介绍了使用 r 将两个变量的值组合在一起以创建一个新变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我需要通过组合两个现有变量的值来创建一个新变量

I need to create a new variable by combining the values of two existing variables

anim <- c(1,2,3,4,5,6,7,8,9,10)
pgrp <- c(1,3,2,4,2,3,1,2,4,3)
fos <- c(2,1,1,2,1,2,1,2,2,1)
data <- data.frame(anim,pgrp,fos)
data
   anim pgrp fos
1     1    1   2
2     2    3   1
3     3    2   1
4     4    4   2
5     5    2   1
6     6    3   2
7     7    1   1
8     8    2   2
9     9    4   2
10   10    3   1

我需要我的新变量pf"来获取pgrp"和fos"的值,如下所示

I need my new variable "pf" to take the values of "pgrp" and "fos" as shown below

data
   anim pgrp fos pf
1     1    1   2 12
2     2    3   1 31
3     3    2   1 21
4     4    4   2 42
5     5    2   1 21
6     6    3   2 32
7     7    1   1 11
8     8    2   2 22
9     9    4   2 42
10   10    3   1 31

推荐答案

如果您的数据框名为 x 只需将它们粘贴在一起(强制转换为字符),然后转换为数字

If your dataframe is called x just paste them together (coerces to character) and then convert to numeric

x$pf <- as.numeric(paste(x$pgrp, x$fos, sep = ""))

(不要使用数据"作为名称,那已经是一个函数了.)

(Do not use "data" as a name, that is a function already.)

这篇关于使用 r 将两个变量的值组合在一起以创建一个新变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-28 06:54:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1169716.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   组合   创建一个   两个

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!