R中基于行值和类别的条件计算 [英] Conditional calculation in R based on Row values and categories

查看:69
本文介绍了R中基于行值和类别的条件计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个数据帧:

df<-data.frame(a=c("a1","a2","a3","a4","b1","b2","b3","b4","a1","a2","a3","a4","b1","b2","b3","b4"), b=c("x1","x2","x3","total","x1","x2","x3","total", "x1","x2","x3","total","x1","x2","x3","total"), reg=c("A","A","A","A","A","A","A","A","B", "B","B","B","B","B","B","B"), c=c(1:16))

如下所示:

    a     b reg  c
1  a1    x1   A  1
2  a2    x2   A  2
3  a3    x3   A  3
4  a4 total   A  4
5  b1    x1   A  5
6  b2    x2   A  6
7  b3    x3   A  7
8  b4 total   A  8
9  a1    x1   B  9
10 a2    x2   B 10
11 a3    x3   B 11
12 a4 total   B 12
13 b1    x1   B 13
14 b2    x2   B 14
15 b3    x3   B 15
16 b4 total   B 16

列'a','b'和'reg'是类别变量。我想做的是创建一个新列,该列将x(i)划分为 reg'中的每个类别,其中i = 1,2,3用'total'(x(i)/ total)并在 a'列中。

columns 'a', 'b' and 'reg' are categorical variables. What I want to do is to create a new column which divides x(i), where i=1,2,3 with 'total' (x(i)/total) for each category in reg' and ina' columns.

有人可以帮我吗?

推荐答案

假设您的df像您的示例一样被排序。

Assuming your df is ordered like your example .

library(zoo)
df$NEW=df$c
df$NEW[df$b!='total']=NA
df$NEW=na.locf(df$NEW,fromLast=T,na.rm=F)
df$NEW=df$c/df$NEW

df
    a     b reg  c       NEW
1  a1    x1   A  1 0.2500000
2  a2    x2   A  2 0.5000000
3  a3    x2   A  3 0.7500000
4  a4 total   A  4 1.0000000
5  b1    x1   A  5 0.6250000
6  b2    x2   A  6 0.7500000
7  b3    x2   A  7 0.8750000
8  b4 total   A  8 1.0000000
9  a1    x1   B  9 0.7500000
10 a2    x2   B 10 0.8333333
11 a3    x2   B 11 0.9166667
12 a4 total   B 12 1.0000000
13 b1    x1   B 13 0.8125000
14 b2    x2   B 14 0.8750000
15 b3    x2   B 15 0.9375000
16 b4 total   B 16 1.0000000

根据Op的解释,以下内容用于处理他/她的真实数据。(来自OP)

Base on Op's explanation ,Below are working for the real data of he/she.(From OP)

data1$shares<-NA 
id<-which(data1$Occupation=='Total') 
data1$shares[id]<-data1$2014[id]
data1$shares=na.locf(data1$shares,fromLast=T,na.rm=F) 
data1$shares=data1$2014/data1$shares

这篇关于R中基于行值和类别的条件计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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