修改数据框中的变量,仅适用于某个因子的某些级别(可能使用dplyr)

时间:2016-08-09 09:10:41

标签: r dataframe dplyr

示例df:

df <- data.frame(x = c(runif(10,0,2*pi),runif(10,0,360)), group = gl(n = 2, k = 10, labels =c("A","B")))

我想仅为群组x修改A(将其转换为度数)。使用base我就是这样做:

df <- within(df,x[group == "A"] <- x[group == "A"]*180/pi)

我想知道是否可以通过dplyr进行此操作。这是错的:

df <- df %>% filter(group == "A") %>% mutate(x = x*180/pi)

因为它只返回df的子集group == "A"。是否有一种(简单)方法可以做到这一点,或者这是base胜过dplyr以便于使用的情况?

1 个答案:

答案 0 :(得分:3)

我们可以使用 protected void Button5_Click(object sender, EventArgs e) { dynamic rpt = new ReportDocument(); ApplyCRLogin(rpt); DataSet dtu = new DataSet(); // Your Stored Procedure Here // Bind dtu to the ObjReport rpt .Database.Tables["Command"].SetDataSource(dtu.Tables[0]); // Here Command is name which you can see inside Field Explorer in Crystal Report Design Mode // Then Pass your SP parametrs rpt.SetParameterValue("@dtFromDate", txtFromDate.Text); rpt.SetParameterValue("@dtToDate", txtToDate.Text); //After this Export your Crstal Report to PDF ExportToPDF(rpt); } public void ApplyCRLogin(CrystalDecisions.CrystalReports.Engine.ReportDocument oRpt) { CrystalDecisions.CrystalReports.Engine.Database oCRDb = oRpt.Database; CrystalDecisions.CrystalReports.Engine.Tables oCRTables = oCRDb.Tables; CrystalDecisions.Shared.TableLogOnInfo oCRTableLogonInfo; CrystalDecisions.Shared.ConnectionInfo oCRConnectionInfo = new CrystalDecisions.Shared.ConnectionInfo(); oCRConnectionInfo.DatabaseName = "DatabaseName"; oCRConnectionInfo.ServerName = "DBSRV_NAME"; oCRConnectionInfo.UserID = "UserID"; oCRConnectionInfo.Password = "Password"; foreach (CrystalDecisions.CrystalReports.Engine.Table oCRTable in oCRTables) { oCRTableLogonInfo = oCRTable.LogOnInfo; oCRTableLogonInfo.ConnectionInfo = oCRConnectionInfo; oCRTable.ApplyLogOnInfo(oCRTableLogonInfo); } } 来创建逻辑条件,并根据它进行算术运算或ifelse返回原始值。

else

或者@AlexIoannides提到,可以使用df %>% mutate(x = ifelse(group=="A", x*180/pi, x)) 中的if_else,因此dplyr应该得到处理。

type中,这可以通过就地分配来完成,并且应该更有效率。

data.table