将表元素或表数组添加到R中的数据框 [英] Adding elements of tables or arrays of tables to a dataframe in R

查看:108
本文介绍了将表元素或表数组添加到R中的数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何在下面的代码中将 fpc 对象)的元素添加为新列到 out out的相关行?

I was wondering how I could add elements of fpc (table object) in my code below as new column to the relevant rows of out?

通过 out 的相关行,我的意思是与 fpc 表名匹配的行。例如,对于 out 中的所有行,其中有 F High code>, fpc 将为 0.02027469

By relevant rows of out, I mean rows that match the fpc table names. For example, for all rows in out where there is an F and an High, fpc will be 0.02027469.

out 中的所有行,其中有 M Medium fpc 将为 0.01984979 ,依此类推。

Or for all rows in out where there is an M and an Medium, fpc will be 0.01984979, and so on.

这是

注意:这是一个玩具数据。 fpc 也可以是一个表数组(请参见下文)。因此,非常感谢功能解决方案。

Note: This is a toy data. fpc could be an array of tables as well (see below). So, a functional solution is appreciated.

d <- read.csv('https://raw.githubusercontent.com/rnorouzian/d/master/su.csv')

out <- read.csv('https://raw.githubusercontent.com/rnorouzian/d/master/out.csv')

vars <- c("gender", "pre")

tt1 <- table(d[vars])

tt2 <- table(out[vars])

( fpc <- tt2/tt1 )

     pre
gender       High        Low     Medium
     F 0.02027469 0.01974522 0.02009274
     M 0.02014295 0.01991008 0.01984979


########## PLEASE NOTE: `fpc` could be an array of tables as shown below:

vars <- c("gender", "pre", "sector")

tt11 <- table(d[vars])

tt22 <- table(out[vars])

( fpc2 <- tt22/tt11 )


推荐答案

在这里,我们只需要强制到data.frame与 as.data.frame ,它也适用于2d和3d数组

Here, we just need to coerce the table to data.frame with as.data.frame, it would work with 2d and 3d arrays as well

out1 <- merge(out, as.data.frame(fpc2), all.x = TRUE)
names(out1)[names(out1)== "Freq"] <- "fpc"




使用更新的案例


With the updated case

 l1 <- length(dimnames(fpc))
 nm1 <- names(dimnames(fpc))
 if(l1 == 1 &&  nm1 == "") {
      names(dimnames(fpc)) <- "cname" # change here
   }

现在,我们进行合并

out2 <- merge(out, as.data.frame(fpc))
identical(nrow(out2), nrow(out))
#[1] TRUE

这篇关于将表元素或表数组添加到R中的数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆