如何使用for循环来生成子集数据帧

时间:2017-09-13 10:44:21

标签: r

我有一个由列组成的数据集,包括:指标,值,省,目标号和排名。基于这个数据集,我想制作省级数据集。换句话说,我想制作以省名为标题的数据集的子集。我怎么能用for循环呢?或者还有其他方法吗? 谢谢!

2 个答案:

答案 0 :(得分:1)

将您的数据框名称视为'df',并将您想要拆分为小数据框的列作为'省'使用以下代码

library(plyr)
list_df = dlply(df, "Province", identity)
list2env(list_df,envir=.GlobalEnv)

答案 1 :(得分:0)

欢迎使用堆栈溢出。

假设你有Public Function IndataTest() Dim conn As ADODB.Connection Dim ConnString As String ConnString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Data Source=DB;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Workstation ID=B5037093;Use Encryption for Data=False;Tag with column collation when possible=False;Initial Catalog=DB" Dim sqlstr As String Dim rs As Object Dim cmd As Object Dim ParamId As Object Dim Id As String Id = 1084924 sqlstr = sqlstr & "use DB " sqlstr = sqlstr & "Select * " & vbCrLf sqlstr = sqlstr & "From tblA" & vbCrLf sqlstr = sqlstr & "where fldA = @Id" Set conn = New ADODB.Connection conn.Open ConnString Set cmd = CreateObject("ADODB.Command") cmd.ActiveConnection = conn cmd.CommandText = sqlstr Set ParamId = cmd.CreateParameter("@Id", 129, 1, 52, Id) cmd.Parameters.Append ParamId Set rs = CreateObject("ADODB.Recordset") rs.Open cmd If Not rs.EOF Then ' Transfer result. Sheets("Valuta").Cells(5, 5).CopyFromRecordset rs ' Close the recordset rs.Close Else MsgBox "Error: No records returned.", vbCritical End If ' Clean up If CBool(conn.State And adStateOpen) Then conn.Close Set conn = Nothing Set rs = Nothing End Function 这样:

data.frame

然后您可以使用ex <- data.frame("Indicator" = c(1,1,2,1), "Value" = c(2,3,4,1), "Province" = c("a","a","b","b"), "goal number" = c(1,1,1,1), "ranking" = c(1,1,5,5)) ex Indicator Value Province goal.number ranking 1 1 2 a 1 1 2 1 3 a 1 1 3 2 4 b 1 5 4 1 1 b 1 5 制作subset

的子集
data.frame

以后的问题:请提供reproducible example