Author : tmlab / Date : 2016. 10. 4. 01:20 / Category : Lecture/R 프로그래밍
When working with data you must:
Figure out what you want to do.
Describe those tasks in the form of a computer program.
Execute the program.
The dplyr package makes these steps fast and easy:
By constraining your options, it simplifies how you can think about common data manipulation tasks.
It provides simple “verbs”, functions that correspond to the most common data manipulation tasks, to help you translate those thoughts into code.
It uses efficient data storage backends, so you spend less time waiting for the computer.
This document introduces you to dplyr’s basic set of tools, and shows you how to apply them to data frames. Other vignettes provide more details on specific topics:
databases: Besides in-memory data frames, dplyr also connects to out-of-memory, remote databases. And by translating your R code into the appropriate SQL, it allows you to work with both types of data using the same set of tools.
benchmark-baseball: see how dplyr compares to other tools for data manipulation on a realistic use case.
window-functions: a window function is a variation on an aggregation function. Where an aggregate function uses n
inputs to produce 1 output, a window function uses n
inputs to produce n
outputs.
To explore the basic data manipulation verbs of dplyr, we’ll start with the built in nycflights13
data frame. This dataset contains all 336776 flights that departed from New York City in 2013. The data comes from the US Bureau of Transportation Statistics, and is documented in?nycflights13
#install.packages("nycflights13")
library(nycflights13)
library(dplyr)
##
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
dim(flights)
## [1] 336776 19
head(flights)
## Source: local data frame [6 x 19]
##
## year month day dep_time sched_dep_time dep_delay arr_time
## (int) (int) (int) (int) (int) (dbl) (int)
## 1 2013 1 1 517 515 2 830
## 2 2013 1 1 533 529 4 850
## 3 2013 1 1 542 540 2 923
## 4 2013 1 1 544 545 -1 1004
## 5 2013 1 1 554 600 -6 812
## 6 2013 1 1 554 558 -4 740
## Variables not shown: sched_arr_time (int), arr_delay (dbl), carrier (chr),
## flight (int), tailnum (chr), origin (chr), dest (chr), air_time (dbl),
## distance (dbl), hour (dbl), minute (dbl), time_hour (time)
dplyr can work with data frames as is, but if you’re dealing with large data, it’s worthwhile to convert them to a tbl_df
: this is a wrapper around a data frame that won’t accidentally print a lot of data to the screen.
Dplyr aims to provide a function for each basic verb of data manipulation:
filter()
(and slice()
)arrange()
select()
(and rename()
)distinct()
mutate()
(and transmute()
)summarise()
sample_n()
and sample_frac()
If you’ve used plyr before, many of these will be familar.
filter()
filter()
allows you to select a subset of rows in a data frame. The first argument is the name of the data frame. The second and subsequent arguments are the expressions that filter the data frame:
For example, we can select all flights on January 1st with:
filter(flights, month == 1, day == 1)
## Source: local data frame [842 x 19]
##
## year month day dep_time sched_dep_time dep_delay arr_time
## (int) (int) (int) (int) (int) (dbl) (int)
## 1 2013 1 1 517 515 2 830
## 2 2013 1 1 533 529 4 850
## 3 2013 1 1 542 540 2 923
## 4 2013 1 1 544 545 -1 1004
## 5 2013 1 1 554 600 -6 812
## 6 2013 1 1 554 558 -4 740
## 7 2013 1 1 555 600 -5 913
## 8 2013 1 1 557 600 -3 709
## 9 2013 1 1 557 600 -3 838
## 10 2013 1 1 558 600 -2 753
## .. ... ... ... ... ... ... ...
## Variables not shown: sched_arr_time (int), arr_delay (dbl), carrier (chr),
## flight (int), tailnum (chr), origin (chr), dest (chr), air_time (dbl),
## distance (dbl), hour (dbl), minute (dbl), time_hour (time)
This is equivalent to the more verbose code in base R:
flights[flights$month == 1 & flights$day == 1, ]
filter()
works similarly to subset()
except that you can give it any number of filtering conditions, which are joined together with & (not && which is easy to do accidentally!). You can also use other boolean operators:
filter(flights, month == 1 | month == 2)
To select rows by position, use slice():
slice(flights, 1:10)
## Source: local data frame [10 x 19]
##
## year month day dep_time sched_dep_time dep_delay arr_time
## (int) (int) (int) (int) (int) (dbl) (int)
## 1 2013 1 1 517 515 2 830
## 2 2013 1 1 533 529 4 850
## 3 2013 1 1 542 540 2 923
## 4 2013 1 1 544 545 -1 1004
## 5 2013 1 1 554 600 -6 812
## 6 2013 1 1 554 558 -4 740
## 7 2013 1 1 555 600 -5 913
## 8 2013 1 1 557 600 -3 709
## 9 2013 1 1 557 600 -3 838
## 10 2013 1 1 558 600 -2 753
## Variables not shown: sched_arr_time (int), arr_delay (dbl), carrier (chr),
## flight (int), tailnum (chr), origin (chr), dest (chr), air_time (dbl),
## distance (dbl), hour (dbl), minute (dbl), time_hour (time)
arrange()
arrange()
works similarly to filter()
except that instead of filtering or selecting rows, it reorders them. It takes a data frame, and a set of column names (or more complicated expressions) to order by. If you provide more than one column name, each additional column will be used to break ties in the values of preceding columns:
arrange(flights, year, month, day)
## Source: local data frame [336,776 x 19]
##
## year month day dep_time sched_dep_time dep_delay arr_time
## (int) (int) (int) (int) (int) (dbl) (int)
## 1 2013 1 1 517 515 2 830
## 2 2013 1 1 533 529 4 850
## 3 2013 1 1 542 540 2 923
## 4 2013 1 1 544 545 -1 1004
## 5 2013 1 1 554 600 -6 812
## 6 2013 1 1 554 558 -4 740
## 7 2013 1 1 555 600 -5 913
## 8 2013 1 1 557 600 -3 709
## 9 2013 1 1 557 600 -3 838
## 10 2013 1 1 558 600 -2 753
## .. ... ... ... ... ... ... ...
## Variables not shown: sched_arr_time (int), arr_delay (dbl), carrier (chr),
## flight (int), tailnum (chr), origin (chr), dest (chr), air_time (dbl),
## distance (dbl), hour (dbl), minute (dbl), time_hour (time)
Use desc()
to order a column in descending order:
arrange(flights, desc(arr_delay))
## Source: local data frame [336,776 x 19]
##
## year month day dep_time sched_dep_time dep_delay arr_time
## (int) (int) (int) (int) (int) (dbl) (int)
## 1 2013 1 9 641 900 1301 1242
## 2 2013 6 15 1432 1935 1137 1607
## 3 2013 1 10 1121 1635 1126 1239
## 4 2013 9 20 1139 1845 1014 1457
## 5 2013 7 22 845 1600 1005 1044
## 6 2013 4 10 1100 1900 960 1342
## 7 2013 3 17 2321 810 911 135
## 8 2013 7 22 2257 759 898 121
## 9 2013 12 5 756 1700 896 1058
## 10 2013 5 3 1133 2055 878 1250
## .. ... ... ... ... ... ... ...
## Variables not shown: sched_arr_time (int), arr_delay (dbl), carrier (chr),
## flight (int), tailnum (chr), origin (chr), dest (chr), air_time (dbl),
## distance (dbl), hour (dbl), minute (dbl), time_hour (time)
dplyr::arrange()
works the same way as plyr::arrange()
. It’s a straighforward wrapper around order()
that requires less typing. The previous code is equivalent to:
flights[order(flights$year, flights$month, flights$day), ]
flights[order(desc(flights$arr_delay)), ]
select()
Often you work with large datasets with many columns but only a few are actually of interest to you. select()
allows you to rapidly zoom in on a useful subset using operations that usually only work on numeric variable positions:
# Select columns by name
select(flights, year, month, day)
## Source: local data frame [336,776 x 3]
##
## year month day
## (int) (int) (int)
## 1 2013 1 1
## 2 2013 1 1
## 3 2013 1 1
## 4 2013 1 1
## 5 2013 1 1
## 6 2013 1 1
## 7 2013 1 1
## 8 2013 1 1
## 9 2013 1 1
## 10 2013 1 1
## .. ... ... ...
select(flights, year:day)
## Source: local data frame [336,776 x 3]
##
## year month day
## (int) (int) (int)
## 1 2013 1 1
## 2 2013 1 1
## 3 2013 1 1
## 4 2013 1 1
## 5 2013 1 1
## 6 2013 1 1
## 7 2013 1 1
## 8 2013 1 1
## 9 2013 1 1
## 10 2013 1 1
## .. ... ... ...
select(flights, -(year:day))
## Source: local data frame [336,776 x 16]
##
## dep_time sched_dep_time dep_delay arr_time sched_arr_time arr_delay
## (int) (int) (dbl) (int) (int) (dbl)
## 1 517 515 2 830 819 11
## 2 533 529 4 850 830 20
## 3 542 540 2 923 850 33
## 4 544 545 -1 1004 1022 -18
## 5 554 600 -6 812 837 -25
## 6 554 558 -4 740 728 12
## 7 555 600 -5 913 854 19
## 8 557 600 -3 709 723 -14
## 9 557 600 -3 838 846 -8
## 10 558 600 -2 753 745 8
## .. ... ... ... ... ... ...
## Variables not shown: carrier (chr), flight (int), tailnum (chr), origin
## (chr), dest (chr), air_time (dbl), distance (dbl), hour (dbl), minute
## (dbl), time_hour (time)
This function works similarly to the select argument in base::subset()
. Because the dplyr philosophy is to have small functions that do one thing well, it’s its own function in dplyr.
There are a number of helper functions you can use within select()
, like starts_with()
, ends_with()
, matches()
and contains()
. These let you quickly match larger blocks of variables that meet some criterion. See ?select
for more details.
You can rename variables with select()
by using named arguments:
select(flights, tail_num = tailnum)
## Source: local data frame [336,776 x 1]
##
## tail_num
## (chr)
## 1 N14228
## 2 N24211
## 3 N619AA
## 4 N804JB
## 5 N668DN
## 6 N39463
## 7 N516JB
## 8 N829AS
## 9 N593JB
## 10 N3ALAA
## .. ...
But because select()
drops all the variables not explicitly mentioned, it’s not that useful. Instead, use rename()
:
rename(flights, tail_num = tailnum)
## Source: local data frame [336,776 x 19]
##
## year month day dep_time sched_dep_time dep_delay arr_time
## (int) (int) (int) (int) (int) (dbl) (int)
## 1 2013 1 1 517 515 2 830
## 2 2013 1 1 533 529 4 850
## 3 2013 1 1 542 540 2 923
## 4 2013 1 1 544 545 -1 1004
## 5 2013 1 1 554 600 -6 812
## 6 2013 1 1 554 558 -4 740
## 7 2013 1 1 555 600 -5 913
## 8 2013 1 1 557 600 -3 709
## 9 2013 1 1 557 600 -3 838
## 10 2013 1 1 558 600 -2 753
## .. ... ... ... ... ... ... ...
## Variables not shown: sched_arr_time (int), arr_delay (dbl), carrier (chr),
## flight (int), tail_num (chr), origin (chr), dest (chr), air_time (dbl),
## distance (dbl), hour (dbl), minute (dbl), time_hour (time)
A common use of select()
is to find the values of a set of variables. This is particularly useful in conjunction with the distinct()
verb which only returns the unique values in a table.
distinct(select(flights, tailnum))
## Source: local data frame [4,044 x 1]
##
## tailnum
## (chr)
## 1 N14228
## 2 N24211
## 3 N619AA
## 4 N804JB
## 5 N668DN
## 6 N39463
## 7 N516JB
## 8 N829AS
## 9 N593JB
## 10 N3ALAA
## .. ...
distinct(select(flights, origin, dest))
## Source: local data frame [224 x 2]
##
## origin dest
## (chr) (chr)
## 1 EWR IAH
## 2 LGA IAH
## 3 JFK MIA
## 4 JFK BQN
## 5 LGA ATL
## 6 EWR ORD
## 7 EWR FLL
## 8 LGA IAD
## 9 JFK MCO
## 10 LGA ORD
## .. ... ...
(This is very similar to base::unique()
but should be much faster.)
mutate()
Besides selecting sets of existing columns, it’s often useful to add new columns that are functions of existing columns. This is the job ofmutate()
:
mutate(flights,
gain = arr_delay - dep_delay,
speed = distance / air_time * 60)
## Source: local data frame [336,776 x 21]
##
## year month day dep_time sched_dep_time dep_delay arr_time
## (int) (int) (int) (int) (int) (dbl) (int)
## 1 2013 1 1 517 515 2 830
## 2 2013 1 1 533 529 4 850
## 3 2013 1 1 542 540 2 923
## 4 2013 1 1 544 545 -1 1004
## 5 2013 1 1 554 600 -6 812
## 6 2013 1 1 554 558 -4 740
## 7 2013 1 1 555 600 -5 913
## 8 2013 1 1 557 600 -3 709
## 9 2013 1 1 557 600 -3 838
## 10 2013 1 1 558 600 -2 753
## .. ... ... ... ... ... ... ...
## Variables not shown: sched_arr_time (int), arr_delay (dbl), carrier (chr),
## flight (int), tailnum (chr), origin (chr), dest (chr), air_time (dbl),
## distance (dbl), hour (dbl), minute (dbl), time_hour (time), gain (dbl),
## speed (dbl)
dplyr::mutate()
works the same way as plyr::mutate()
and similarly to base::transform()
. The key difference between mutate()
andtransform()
is that mutate allows you to refer to columns that you’ve just created:
mutate(flights,
gain = arr_delay - dep_delay,
gain_per_hour = gain / (air_time / 60)
)
## Source: local data frame [336,776 x 21]
##
## year month day dep_time sched_dep_time dep_delay arr_time
## (int) (int) (int) (int) (int) (dbl) (int)
## 1 2013 1 1 517 515 2 830
## 2 2013 1 1 533 529 4 850
## 3 2013 1 1 542 540 2 923
## 4 2013 1 1 544 545 -1 1004
## 5 2013 1 1 554 600 -6 812
## 6 2013 1 1 554 558 -4 740
## 7 2013 1 1 555 600 -5 913
## 8 2013 1 1 557 600 -3 709
## 9 2013 1 1 557 600 -3 838
## 10 2013 1 1 558 600 -2 753
## .. ... ... ... ... ... ... ...
## Variables not shown: sched_arr_time (int), arr_delay (dbl), carrier (chr),
## flight (int), tailnum (chr), origin (chr), dest (chr), air_time (dbl),
## distance (dbl), hour (dbl), minute (dbl), time_hour (time), gain (dbl),
## gain_per_hour (dbl)
transform(flights,
gain = arr_delay - dep_delay,
gain_per_hour = gain / (air_time / 60)
)
## Error in eval(expr, envir, enclos): 객체 'gain'를 찾을 수 없습니다
If you only want to keep the new variables, use transmute()
:
transmute(flights,
gain = arr_delay - dep_delay,
gain_per_hour = gain / (air_time / 60)
)
## Source: local data frame [336,776 x 2]
##
## gain gain_per_hour
## (dbl) (dbl)
## 1 9 2.378855
## 2 16 4.229075
## 3 31 11.625000
## 4 -17 -5.573770
## 5 -19 -9.827586
## 6 16 6.400000
## 7 24 9.113924
## 8 -11 -12.452830
## 9 -5 -2.142857
## 10 10 4.347826
## .. ... ...
summarise()
The last verb is summarise()
. It collapses a data frame to a single row (this is exactly equivalent to plyr::summarise()
):
summarise(flights,
delay = mean(dep_delay, na.rm = TRUE))
## Source: local data frame [1 x 1]
##
## delay
## (dbl)
## 1 12.63907
Below, we’ll see how this verb can be very useful.
sample_n()
and sample_frac()
You can use sample_n()
and sample_frac()
to take a random sample of rows: use sample_n()
for a fixed number and sample_frac()
for a fixed fraction.
sample_n(flights, 10)
## Source: local data frame [10 x 19]
##
## year month day dep_time sched_dep_time dep_delay arr_time
## (int) (int) (int) (int) (int) (dbl) (int)
## 1 2013 10 20 2028 2030 -2 2143
## 2 2013 12 13 730 730 0 1053
## 3 2013 3 10 1500 1505 -5 1817
## 4 2013 12 8 1617 1617 0 1914
## 5 2013 9 19 834 837 -3 1035
## 6 2013 4 28 1037 1010 27 1142
## 7 2013 2 22 1701 1700 1 1847
## 8 2013 12 22 1824 1724 60 2115
## 9 2013 12 23 1150 1125 25 1348
## 10 2013 2 8 606 610 -4 714
## Variables not shown: sched_arr_time (int), arr_delay (dbl), carrier (chr),
## flight (int), tailnum (chr), origin (chr), dest (chr), air_time (dbl),
## distance (dbl), hour (dbl), minute (dbl), time_hour (time)
sample_frac(flights, 0.01)
## Source: local data frame [3,368 x 19]
##
## year month day dep_time sched_dep_time dep_delay arr_time
## (int) (int) (int) (int) (int) (dbl) (int)
## 1 2013 9 11 1105 1115 -10 1345
## 2 2013 3 5 2236 2129 67 2335
## 3 2013 8 24 857 900 -3 1114
## 4 2013 6 18 2159 2045 74 11
## 5 2013 5 23 NA 1724 NA NA
## 6 2013 7 21 613 615 -2 755
## 7 2013 10 10 1700 1705 -5 1815
## 8 2013 9 4 819 825 -6 1010
## 9 2013 7 22 1038 1030 8 1302
## 10 2013 4 17 558 605 -7 722
## .. ... ... ... ... ... ... ...
## Variables not shown: sched_arr_time (int), arr_delay (dbl), carrier (chr),
## flight (int), tailnum (chr), origin (chr), dest (chr), air_time (dbl),
## distance (dbl), hour (dbl), minute (dbl), time_hour (time)
Use replace = TRUE
to perform a bootstrap sample. If needed, you can weight the sample with the weight
argument.
You may have noticed that the syntax and function of all these verbs are very similar:
The first argument is a data frame.
The subsequent arguments describe what to do with the data frame. Notice that you can refer to columns in the data frame directly without using $.
The result is a new data frame
Together these properties make it easy to chain together multiple simple steps to achieve a complex result.
These five functions provide the basis of a language of data manipulation. At the most basic level, you can only alter a tidy data frame in five useful ways: you can reorder the rows (arrange()
), pick observations and variables of interest (filter() and select()
), add new variables that are functions of existing variables (mutate()
), or collapse many values to a summary (summarise()
). The remainder of the language comes from applying the five functions to different types of data. For example, I’ll discuss how these functions work with grouped data.
These verbs are useful on their own, but they become really powerful when you apply them to groups of observations within a dataset. In dplyr, you do this by with the group_by()
function. It breaks down a dataset into specified groups of rows. When you then apply the verbs above on the resulting object they’ll be automatically applied “by group”. Most importantly, all this is achieved by using the same exact syntax you’d use with an ungrouped object.
Grouping affects the verbs as follows:
grouped select()
is the same as ungrouped select(), except that grouping variables are always retained.
grouped arrange()
orders first by the grouping variables
mutate()
and filter()
are most useful in conjunction with window functions (like rank()
, or min(x) == x
). They are described in detail invignette("window-functions")
.
sample_n()
and sample_frac()
sample the specified number/fraction of rows in each group.
slice()
extracts rows within each group.
summarise()
is powerful and easy to understand, as described in more detail below.
In the following example, we split the complete dataset into individual planes and then summarise each plane by counting the number of flights (count = n()
) and computing the average distance (dist = mean(Distance, na.rm = TRUE)
) and arrival delay (delay = mean(ArrDelay, na.rm = TRUE)
). We then use ggplot2 to display the output.
library(ggplot2)
by_tailnum <- group_by(flights, tailnum)
delay <- summarise(by_tailnum,
count = n(),
dist = mean(distance, na.rm = TRUE),
delay = mean(arr_delay, na.rm = TRUE))
delay <- filter(delay, count > 20, dist < 2000)
# Interestingly, the average delay is only slightly related to the
# average distance flown by a plane.
ggplot(delay, aes(dist, delay)) +
geom_point(aes(size = count), alpha = 1/2) +
geom_smooth() +
scale_size_area()
## Warning: Removed 1 rows containing non-finite values (stat_smooth).
## Warning: Removed 1 rows containing missing values (geom_point).
You use summarise()
with aggregate functions, which take a vector of values and return a single number. There are many useful examples of such functions in base R like min()
, max()
, mean()
, sum()
, sd()
, median()
, and IQR()
. dplyr provides a handful of others:
n()
: the number of observations in the current group
n_distinct(x)
:the number of unique values in x.
first(x)
, last(x)
and nth(x, n)
- these work similarly to x[1]
, x[length(x)]
, and x[n]
but give you more control over the result if the value is missing.
For example, we could use these to find the number of planes and the number of flights that go to each possible destination:
destinations <- group_by(flights, dest)
summarise(destinations,
planes = n_distinct(tailnum),
flights = n()
)
## Source: local data frame [105 x 3]
##
## dest planes flights
## (chr) (int) (int)
## 1 ABQ 108 254
## 2 ACK 58 265
## 3 ALB 172 439
## 4 ANC 6 8
## 5 ATL 1180 17215
## 6 AUS 993 2439
## 7 AVL 159 275
## 8 BDL 186 443
## 9 BGR 46 375
## 10 BHM 45 297
## .. ... ... ...
You can also use any function that you write yourself. For performance, dplyr provides optimised C++ versions of many of these functions. If you want to provide your own C++ function, see the hybrid-evaluation vignette for more details.
When you group by multiple variables, each summary peels off one level of the grouping. That makes it easy to progressively roll-up a dataset:
daily <- group_by(flights, year, month, day)
(per_day <- summarise(daily, flights = n()))
## Source: local data frame [365 x 4]
## Groups: year, month [?]
##
## year month day flights
## (int) (int) (int) (int)
## 1 2013 1 1 842
## 2 2013 1 2 943
## 3 2013 1 3 914
## 4 2013 1 4 915
## 5 2013 1 5 720
## 6 2013 1 6 832
## 7 2013 1 7 933
## 8 2013 1 8 899
## 9 2013 1 9 902
## 10 2013 1 10 932
## .. ... ... ... ...
(per_month <- summarise(per_day, flights = sum(flights)))
## Source: local data frame [12 x 3]
## Groups: year [?]
##
## year month flights
## (int) (int) (int)
## 1 2013 1 27004
## 2 2013 2 24951
## 3 2013 3 28834
## 4 2013 4 28330
## 5 2013 5 28796
## 6 2013 6 28243
## 7 2013 7 29425
## 8 2013 8 29327
## 9 2013 9 27574
## 10 2013 10 28889
## 11 2013 11 27268
## 12 2013 12 28135
(per_year <- summarise(per_month, flights = sum(flights)))
## Source: local data frame [1 x 2]
##
## year flights
## (int) (int)
## 1 2013 336776
However you need to be careful when progressively rolling up summaries like this: it’s ok for sums and counts, but you need to think about weighting for means and variances (it’s not possible to do this exactly for medians).
The dplyr API is functional in the sense that function calls don’t have side-effects. You must always save their results. This doesn’t lead to particularly elegant code, especially if you want to do many operations at once. You either have to do it step-by-step:
a1 <- group_by(flights, year, month, day)
a2 <- select(a1, arr_delay, dep_delay)
a3 <- summarise(a2,
arr = mean(arr_delay, na.rm = TRUE),
dep = mean(dep_delay, na.rm = TRUE))
a4 <- filter(a3, arr > 30 | dep > 30)
Or if you don’t want to save the intermediate results, you need to wrap the function calls inside each other:
filter(
summarise(
select(
group_by(flights, year, month, day),
arr_delay, dep_delay
),
arr = mean(arr_delay, na.rm = TRUE),
dep = mean(dep_delay, na.rm = TRUE)
),
arr > 30 | dep > 30
)
## Source: local data frame [49 x 5]
## Groups: year, month [11]
##
## year month day arr dep
## (int) (int) (int) (dbl) (dbl)
## 1 2013 1 16 34.24736 24.61287
## 2 2013 1 31 32.60285 28.65836
## 3 2013 2 11 36.29009 39.07360
## 4 2013 2 27 31.25249 37.76327
## 5 2013 3 8 85.86216 83.53692
## 6 2013 3 18 41.29189 30.11796
## 7 2013 4 10 38.41231 33.02368
## 8 2013 4 12 36.04814 34.83843
## 9 2013 4 18 36.02848 34.91536
## 10 2013 4 19 47.91170 46.12783
## .. ... ... ... ... ...
This is difficult to read because the order of the operations is from inside to out. Thus, the arguments are a long way away from the function. To get around this problem, dplyr provides the %>% operator. x %>% f(y) turns into f(x, y) so you can use it to rewrite multiple operations that you can read left-to-right, top-to-bottom:
flights %>%
group_by(year, month, day) %>%
select(arr_delay, dep_delay) %>%
summarise(
arr = mean(arr_delay, na.rm = TRUE),
dep = mean(dep_delay, na.rm = TRUE)
) %>%
filter(arr > 30 | dep > 30)
## Source: local data frame [49 x 5]
## Groups: year, month [11]
##
## year month day arr dep
## (int) (int) (int) (dbl) (dbl)
## 1 2013 1 16 34.24736 24.61287
## 2 2013 1 31 32.60285 28.65836
## 3 2013 2 11 36.29009 39.07360
## 4 2013 2 27 31.25249 37.76327
## 5 2013 3 8 85.86216 83.53692
## 6 2013 3 18 41.29189 30.11796
## 7 2013 4 10 38.41231 33.02368
## 8 2013 4 12 36.04814 34.83843
## 9 2013 4 18 36.02848 34.91536
## 10 2013 4 19 47.91170 46.12783
## .. ... ... ... ... ...
As well as data frames, dplyr works with data that is stored in other ways, like data tables, databases and multidimensional arrays.
dplyr also provides data table methods for all verbs. If you’re using data.tables already this lets you to use dplyr syntax for data manipulation, and data.table for everything else.
For multiple operations, data.table can be faster because you usually use it with multiple verbs simultaneously. For example, with data table you can do a mutate and a select in a single step. It’s smart enough to know that there’s no point in computing the new variable for rows you’re about to throw away.
The advantages of using dplyr with data tables are:
For common data manipulation tasks, it insulates you from the reference semantics of data.tables, and protects you from accidentally modifying your data.
Instead of one complex method built on the subscripting operator ([
), it provides many simple methods.
dplyr also allows you to use the same verbs with a remote database. It takes care of generating the SQL for you so that you can avoid the cognitive challenge of constantly switching between languages. See the databases vignette for more details.
Compared to DBI and the database connection algorithms:
tbl_cube()
provides an experimental interface to multidimensional arrays or data cubes. If you’re using this form of data in R, please get in touch so I can better understand your needs.
Compared to all existing options, dplyr:
abstracts away how your data is stored, so that you can work with data frames, data tables and remote databases using the same set of functions. This lets you focus on what you want to achieve, not on the logistics of data storage.
provides a thoughtful default print() method that doesn’t automatically print pages of data to the screen (this was inspired by data table’s output).
Compared to base functions:
dplyr is much more consistent; functions have the same interface. So once you’ve mastered one, you can easily pick up the others
base functions tend to be based around vectors; dplyr is based around data frames
Compared to plyr, dplyr:
is much much faster
provides a better thought out set of joins
only provides tools for working with data frames (e.g. most of dplyr is equivalent to ddply()
+ various functions, do()
is equivalent todlply()
)
Compared to virtual data frame approaches:
it doesn’t pretend that you have a data frame: if you want to run lm etc, you’ll still need to manually pull down the data
it doesn’t provide methods for R summary functions (e.g. mean(), or sum())
There are four fundamental functions of data tidying:
gather()
takes multiple columns, and gathers them into key-value pairs: it makes “wide” data longerspread()
takes two columns (key & value) and spreads in to multiple columns, it makes “long” data widerseparate()
splits a single column into multiple columnsunite()
combines multiple columns into a single columnObjective: Reshaping wide format to long format
Description: There are times when our data is considered unstacked and a common attribute of concern is spread out across columns. To reformat the data such that these common attributes are gathered together as a single variable, the gather()
function will take multiple columns and collapse them into key-value pairs, duplicating all other columns as needed.
Complement to: spread()
Function: gather(data, key, value, ..., na.rm = FALSE, convert = FALSE)
Same as: data %>% gather(key, value, ..., na.rm = FALSE, convert = FALSE)
Arguments:
data: data frame
key: column name representing new variable
value: column name representing variable values
...: names of columns to gather (or not gather)
na.rm: option to remove observations with missing values (represented by NAs)
convert: if TRUE will automatically convert values to logical, integer, numeric, complex or
factor as appropriate
We’ll start with the following data set:
Group <- c(rep(1,4),rep(2,4),rep(3,4))
Year <- c(2006:2009,2006:2009,2006:2009)
Qtr.1 <- c(15,12,22,10,12,16,13,23,11,13,17,14)
Qtr.2 <- c(16,13,22,14,13,14,11,20,12,11,12,9)
Qtr.3 <- c(19,27,24,20,25,21,29,26,22,27,23,31)
Qtr.4 <- c(17,23,20,16,18,19,15,20,16,21,19,24)
DF <- data.frame(Group,Year,Qtr.1,Qtr.2,Qtr.3,Qtr.4)
DF
## Group Year Qtr.1 Qtr.2 Qtr.3 Qtr.4
## 1 1 2006 15 16 19 17
## 2 1 2007 12 13 27 23
## 3 1 2008 22 22 24 20
## 4 1 2009 10 14 20 16
## 5 2 2006 12 13 25 18
## 6 2 2007 16 14 21 19
## 7 2 2008 13 11 29 15
## 8 2 2009 23 20 26 20
## 9 3 2006 11 12 22 16
## 10 3 2007 13 11 27 21
## 11 3 2008 17 12 23 19
## 12 3 2009 14 9 31 24
This data is considered wide since the time variable (represented as quarters) is structured such that each quarter represents a variable. To re-structure the time component as an individual variable, we can gather each quarter within one column variable and also gather the values associated with each quarter in a second column variable.
#install.packages("tidyr")
library(tidyr)
long_DF <- DF %>% gather(Quarter, Revenue, Qtr.1:Qtr.4)
head(long_DF, 24) # note, for brevity, I only show the data for the first two years
## Group Year Quarter Revenue
## 1 1 2006 Qtr.1 15
## 2 1 2007 Qtr.1 12
## 3 1 2008 Qtr.1 22
## 4 1 2009 Qtr.1 10
## 5 2 2006 Qtr.1 12
## 6 2 2007 Qtr.1 16
## 7 2 2008 Qtr.1 13
## 8 2 2009 Qtr.1 23
## 9 3 2006 Qtr.1 11
## 10 3 2007 Qtr.1 13
## 11 3 2008 Qtr.1 17
## 12 3 2009 Qtr.1 14
## 13 1 2006 Qtr.2 16
## 14 1 2007 Qtr.2 13
## 15 1 2008 Qtr.2 22
## 16 1 2009 Qtr.2 14
## 17 2 2006 Qtr.2 13
## 18 2 2007 Qtr.2 14
## 19 2 2008 Qtr.2 11
## 20 2 2009 Qtr.2 20
## 21 3 2006 Qtr.2 12
## 22 3 2007 Qtr.2 11
## 23 3 2008 Qtr.2 12
## 24 3 2009 Qtr.2 9
These all produce the same results:
DF %>% gather(Quarter, Revenue, Qtr.1:Qtr.4)
DF %>% gather(Quarter, Revenue, -Group, -Year)
DF %>% gather(Quarter, Revenue, 3:6)
DF %>% gather(Quarter, Revenue, Qtr.1, Qtr.2, Qtr.3, Qtr.4)
Also note that if you do not supply arguments for na.rm or convert values then the defaults are used
Objective: Splitting a single variable into two
Description: Many times a single column variable will capture multiple variables, or even parts of a variable you just don’t care about. Some examples include:
## Grp_Ind Yr_Mo City_State First_Last Extra_variable
## 1 1.a 2006_Jan Dayton (OH) George Washington XX01person_1
## 2 1.b 2006_Feb Grand Forks (ND) John Adams XX02person_2
## 3 1.c 2006_Mar Fargo (ND) Thomas Jefferson XX03person_3
## 4 2.a 2007_Jan Rochester (MN) James Madison XX04person_4
## 5 2.b 2007_Feb Dubuque (IA) James Monroe XX05person_5
## 6 2.c 2007_Mar Ft. Collins (CO) John Adams XX06person_6
## 7 3.a 2008_Jan Lake City (MN) Andrew Jackson XX07person_7
## 8 3.b 2008_Feb Rushford (MN) Martin Van Buren XX08person_8
## 9 3.c 2008_Mar Unknown William Harrison XX09person_9
In each of these cases, our objective may be to separate characters within the variable string. This can be accomplished using the separate() function which turns a single character column into multiple columns.
Complement to: unite()
Function: separate(data, col, into, sep = " ", remove = TRUE, convert = FALSE)
Same as: data %>% separate(col, into, sep = " ", remove = TRUE, convert = FALSE)
Arguments:
data: data frame
col: column name representing current variable
into: names of variables representing new variables
sep: how to separate current variable (char, num, or symbol)
remove: if TRUE, remove input column from output data frame
convert: if TRUE will automatically convert values to logical, integer, numeric, complex or
factor as appropriate
We can go back to our long_DF dataframe we created above in which way may desire to clean up or separate the Quarter variable.
## Group Year Quarter Revenue
## 1 1 2006 Qtr.1 15
## 2 1 2007 Qtr.1 12
## 3 1 2008 Qtr.1 22
## 4 1 2009 Qtr.1 10
## 5 2 2006 Qtr.1 12
## 6 2 2007 Qtr.1 16
## 7 2 2008 Qtr.1 13
## 8 2 2009 Qtr.1 23
## 9 3 2006 Qtr.1 11
## 10 3 2007 Qtr.1 13
## 11 3 2008 Qtr.1 17
## 12 3 2009 Qtr.1 14
## 13 1 2006 Qtr.2 16
## 14 1 2007 Qtr.2 13
## 15 1 2008 Qtr.2 22
## 16 1 2009 Qtr.2 14
## 17 2 2006 Qtr.2 13
## 18 2 2007 Qtr.2 14
## 19 2 2008 Qtr.2 11
## 20 2 2009 Qtr.2 20
## 21 3 2006 Qtr.2 12
## 22 3 2007 Qtr.2 11
## 23 3 2008 Qtr.2 12
## 24 3 2009 Qtr.2 9
## 25 1 2006 Qtr.3 19
## 26 1 2007 Qtr.3 27
## 27 1 2008 Qtr.3 24
## 28 1 2009 Qtr.3 20
## 29 2 2006 Qtr.3 25
## 30 2 2007 Qtr.3 21
## 31 2 2008 Qtr.3 29
## 32 2 2009 Qtr.3 26
## 33 3 2006 Qtr.3 22
## 34 3 2007 Qtr.3 27
## 35 3 2008 Qtr.3 23
## 36 3 2009 Qtr.3 31
## 37 1 2006 Qtr.4 17
## 38 1 2007 Qtr.4 23
## 39 1 2008 Qtr.4 20
## 40 1 2009 Qtr.4 16
## 41 2 2006 Qtr.4 18
## 42 2 2007 Qtr.4 19
## 43 2 2008 Qtr.4 15
## 44 2 2009 Qtr.4 20
## 45 3 2006 Qtr.4 16
## 46 3 2007 Qtr.4 21
## 47 3 2008 Qtr.4 19
## 48 3 2009 Qtr.4 24
By applying the separate()
function we get the following:
separate_DF <- long_DF %>% separate(Quarter, c("Time_Interval", "Interval_ID"))
head(separate_DF, 10)
## Group Year Time_Interval Interval_ID Revenue
## 1 1 2006 Qtr 1 15
## 2 1 2007 Qtr 1 12
## 3 1 2008 Qtr 1 22
## 4 1 2009 Qtr 1 10
## 5 2 2006 Qtr 1 12
## 6 2 2007 Qtr 1 16
## 7 2 2008 Qtr 1 13
## 8 2 2009 Qtr 1 23
## 9 3 2006 Qtr 1 11
## 10 3 2007 Qtr 1 13
These produce the same results:
long_DF %>% separate(Quarter, c("Time_Interval", "Interval_ID"))
long_DF %>% separate(Quarter, c("Time_Interval", "Interval_ID"), sep = "\\.")
Objective: Merging two variables into one
Description: There may be a time in which we would like to combine the values of two variables. The unite()
function is a convenience function to paste together multiple variable values into one. In essence, it combines two variables of a single observation into one variable.
Complement to: separate()
Function: unite(data, col, ..., sep = " ", remove = TRUE)
Same as: data %>% unite(col, ..., sep = " ", remove = TRUE)
Arguments:
data: data frame
col: column name of new "merged" column
...: names of columns to merge
sep: separator to use between merged values
remove: if TRUE, remove input column from output data frame
Using the separate_DF dataframe we created above, we can re-unite the Time_Interval
and Interval_ID
variables we created and re-create the original Quarter variable we had in the long_DF dataframe.
unite_DF <- separate_DF %>% unite(Quarter, Time_Interval, Interval_ID, sep = ".")
head(unite_DF, 10)
## Group Year Quarter Revenue
## 1 1 2006 Qtr.1 15
## 2 1 2007 Qtr.1 12
## 3 1 2008 Qtr.1 22
## 4 1 2009 Qtr.1 10
## 5 2 2006 Qtr.1 12
## 6 2 2007 Qtr.1 16
## 7 2 2008 Qtr.1 13
## 8 2 2009 Qtr.1 23
## 9 3 2006 Qtr.1 11
## 10 3 2007 Qtr.1 13
These produce the same results:
separate_DF %>% unite(Quarter, Time_Interval, Interval_ID, sep = "_")
separate_DF %>% unite(Quarter, Time_Interval, Interval_ID)
If no spearator is identified, "_" will automatically be used
Objective: Reshaping long format to wide format
Description: There are times when we are required to turn long formatted data into wide formatted data. The spread()
function spreads a key-value pair across multiple columns.
Complement to: gather()
Function: spread(data, key, value, fill = NA, convert = FALSE)
Same as: data %>% spread(key, value, fill = NA, convert = FALSE)
Arguments:
data: data frame
key: column values to convert to multiple columns
value: single column values to convert to multiple columns' values
fill: If there isn't a value for every combination of the other variables and the key
column, this value will be substituted
convert: if TRUE will automatically convert values to logical, integer, numeric, complex or
factor as appropriate
wide_DF <- unite_DF %>% spread(Quarter, Revenue)
head(wide_DF, 24)
## Group Year Qtr.1 Qtr.2 Qtr.3 Qtr.4
## 1 1 2006 15 16 19 17
## 2 1 2007 12 13 27 23
## 3 1 2008 22 22 24 20
## 4 1 2009 10 14 20 16
## 5 2 2006 12 13 25 18
## 6 2 2007 16 14 21 19
## 7 2 2008 13 11 29 15
## 8 2 2009 23 20 26 20
## 9 3 2006 11 12 22 16
## 10 3 2007 13 11 27 21
## 11 3 2008 17 12 23 19
## 12 3 2009 14 9 31 24
밑에 제공된 다음의 문제들을 단계별로 푸시오
-
는 NA값입니다.univ <- read.csv("https://raw.githubusercontent.com/halrequin/data/master/data.csv",stringsAsFactors=F,na.strings="-")
filter()
를 사용하여 경기 지역의 대학교(학제)를 kyung_gi
에 할당하시오.## 조사회차 학제 학교코드 학교명 본분교 학교상태 지역 설립
## 1 201501 대학교 51028000 한경대학교 본교 기존 경기 국립
## 2 201501 대학교 53003000 가톨릭대학교 본교 기존 경기 사립
## 3 201501 대학교 53005000 강남대학교 본교 기존 경기 사립
## 4 201501 대학교 53008000 경기대학교 본교 기존 경기 사립
## 5 201501 대학교 53010000 경동대학교 제4캠퍼스 신설 경기 사립
## 6 201501 대학교 53013000 가천대학교 본교 기존 경기 사립
## 우편번호 주소
## 1 456-749 경기 안성시 중앙로 327(석정동)
## 2 420-743 경기도 부천시 원미구 지봉로 43 (역곡동)
## 3 446-702 경기도 용인시 기흥구 강남로 40 (구갈동, 강남대학교)
## 4 443-760 경기 수원시 영통구 광교산로 154-42 경기대학교
## 5 482-010 경기도 양주시 청담로 95 (고암동)
## 6 461-701 경기 성남시 수정구 성남대로 1342 (복정동)
## 재적.학생.총합 재학생.총합 휴학생.총합 총장.및.전임교원수
## 1 5580 3901 1679 168
## 2 10174 7380 2794 247
## 3 10020 7279 2741 222
## 4 17614 12354 5260 418
## 5 877 620 257 32
## 6 26411 19011 7400 650
kyung_gi
를 가지고 arrange()
를 사용하여 재적학생 총합을 기준으로 내림차순 정렬하여 kyung_gi
에 재할당 하시오.## 조사회차 학제 학교코드 학교명 본분교 학교상태 지역 설립 우편번호
## 1 201501 대학교 53013000 가천대학교 본교 기존 경기 사립 461-701
## 2 201501 대학교 53008000 경기대학교 본교 기존 경기 사립 443-760
## 3 201501 대학교 53030000 단국대학교 본교 기존 경기 사립 448-701
## 4 201501 대학교 53072000 수원대학교 본교 기존 경기 사립 445-743
## 5 201501 대학교 53078000 아주대학교 본교 기존 경기 사립 443-749
## 6 201501 대학교 53123000 한양대학교 분교1 기존 경기 사립 426-791
## 주소
## 1 경기 성남시 수정구 성남대로 1342 (복정동)
## 2 경기 수원시 영통구 광교산로 154-42 경기대학교
## 3 경기도 용인시 수지구 죽전로 152 (죽전동, 단국대학교죽전캠퍼스)
## 4 경기도 화성시 와우안길 17 (봉담읍, 수원대학교)
## 5 경기도 수원시 영통구 월드컵로 206 (원천동, 아주대학교)
## 6 경기도 안산시 상록구 한양대학로 55 (사동, 한양대학교)
## 재적.학생.총합 재학생.총합 휴학생.총합 총장.및.전임교원수
## 1 26411 19011 7400 650
## 2 17614 12354 5260 418
## 3 16946 11975 4971 440
## 4 14978 10705 4273 358
## 5 14141 9954 4187 624
## 6 12910 9232 3678 390
kyung_gi
를 가지고 select()
를 사용하여 학제, 학교명, 학교상태, 지역, 설립 정보를 추출하시오.## 학제 학교명 학교상태 지역 설립
## 1 대학교 가천대학교 기존 경기 사립
## 2 대학교 경기대학교 기존 경기 사립
## 3 대학교 단국대학교 기존 경기 사립
## 4 대학교 수원대학교 기존 경기 사립
## 5 대학교 아주대학교 기존 경기 사립
## 6 대학교 한양대학교 기존 경기 사립
kyung_gi1
에 할당하세요kyung_gi1 <- kyung_gi[complete.cases(kyung_gi$재학생.총합,kyung_gi$총장.및.전임교원수),]
# 숫자로 만들기 위해 자리 수를 나타내는 "," 제거
kyung_gi1
에 mutate()
를 사용하여 총장 및 전임교원 수 대비 재학생 총합 값(재학생 총합/총장 및 전임교원 수)을 rate
라는 열에 저장하여kyung_gi1
에 재할당하시오.## 조사회차 학제 학교코드 학교명 본분교 학교상태 지역 설립 우편번호
## 1 201501 대학교 53013000 가천대학교 본교 기존 경기 사립 461-701
## 2 201501 대학교 53008000 경기대학교 본교 기존 경기 사립 443-760
## 3 201501 대학교 53030000 단국대학교 본교 기존 경기 사립 448-701
## 4 201501 대학교 53072000 수원대학교 본교 기존 경기 사립 445-743
## 5 201501 대학교 53078000 아주대학교 본교 기존 경기 사립 443-749
## 6 201501 대학교 53123000 한양대학교 분교1 기존 경기 사립 426-791
## 주소
## 1 경기 성남시 수정구 성남대로 1342 (복정동)
## 2 경기 수원시 영통구 광교산로 154-42 경기대학교
## 3 경기도 용인시 수지구 죽전로 152 (죽전동, 단국대학교죽전캠퍼스)
## 4 경기도 화성시 와우안길 17 (봉담읍, 수원대학교)
## 5 경기도 수원시 영통구 월드컵로 206 (원천동, 아주대학교)
## 6 경기도 안산시 상록구 한양대학로 55 (사동, 한양대학교)
## 재적.학생.총합 재학생.총합 휴학생.총합 총장.및.전임교원수 rate
## 1 26411 19011 7400 650 29.24769
## 2 17614 12354 5260 418 29.55502
## 3 16946 11975 4971 440 27.21591
## 4 14978 10705 4273 358 29.90223
## 5 14141 9954 4187 624 15.95192
## 6 12910 9232 3678 390 23.67179
kyung_gi1
에 summarise()
를 사용하여 경기 지역 대학교 재학생 평균을 구해보세요## stu_mean
## 1 4959.286
univ
객체에서 10%만큼 sample을 추출하여 univ_sam
에 할당하시오.sample_n()
이나 sample_frac()
을 사용하시오.## 조사회차 학제 학교코드 학교명
## 1895 201501 대학부설대학원 63202C54 남서울대학교 특수대학원
## 602 201501 대학부설대학원 51011B55 부산대학교 치의학전문대학원
## 1287 201501 대학부설대학원 53068D74 성신여자대학교 생애복지대학원
## 978 201501 대학부설대학원 53026650 국민대학교디자인대학원
## 1091 201501 대학부설대학원 53041820 동국대학교 영상대학원(전문)
## 1577 201501 대학부설대학원 53104B57 추계예술대학교 문화예술경영대학원
## 본분교 학교상태 지역 설립 우편번호
## 1895 본교 폐교 충남 사립 330-707
## 602 본교 기존 경남 국립 626-870
## 1287 본교 기존 서울 사립 136-742
## 978 본교 기존 서울 사립 136-702
## 1091 본교 기존 서울 사립 100-715
## 1577 본교 기존 서울 사립 120-763
## 주소
## 1895 충남 천안시 성환읍 대학로 91 남서울대학교
## 602 경상남도 양산시 부산대학로 49 (물금읍, 부산대학교양산캠퍼스) 부산대학교 치의학전문대학원
## 1287 서울특별시 성북구 보문로34다길 2 (돈암동, 성신여자대학교)
## 978 서울 성북구 정릉3동 국민대학교 조형관
## 1091 서울특별시 중구 필동로1길 30 (장충동2가, 동국대학교)
## 1577 서울특별시 서대문구 북아현로11가길 7 (북아현동, 추계예술대학교)
## 재적.학생.총합 재학생.총합 휴학생.총합 총장.및.전임교원수
## 1895 NA NA NA NA
## 602 366 346 20 48
## 1287 79 73 6 1
## 978 300 222 78 NA
## 1091 290 216 74 16
## 1577 79 65 14 2
univ
객체를 사용하여 지역으로 grouping을 하여 모든 교육기관의 갯수와 재학생 평균, 총장 및 전임교원수 평균을 구하여 korean_univ
객체에 할당하시오.## Source: local data frame [6 x 4]
##
## 지역 count stu_mean staff_mean
## (chr) (int) (dbl) (dbl)
## 1 강원 75 1414.971 124.17647
## 2 경기 319 1317.207 71.95597
## 3 경남 86 1379.620 120.67742
## 4 경북 141 1440.458 104.28814
## 5 광주 74 1480.123 128.72414
## 6 대구 51 2129.625 141.04167
library(ggplot2)
univ_gateg <- summarise(group_by(univ,학제),
count = n(),
stu_mean=mean(재적.학생.총합,na.rm=T))
p<-ggplot(univ_gateg, aes(학제,count))
p + geom_point(aes(colour=학제)) + theme(axis.text.x = element_text(angle=270,vjust=1))
kyung_gi
객체에서 각 학교별 본분교 상황, 재적 학생 총합, 재학생 총합, 휴학생 총합, 총장 및 전임교원수를 select()
를 사용하여 test
객체에 할당하세요## 학교명 본분교 재적.학생.총합 재학생.총합 휴학생.총합
## 1 가천대학교 본교 26411 19011 7400
## 2 경기대학교 본교 17614 12354 5260
## 3 단국대학교 본교 16946 11975 4971
## 4 수원대학교 본교 14978 10705 4273
## 5 아주대학교 본교 14141 9954 4187
## 6 한양대학교 분교1 12910 9232 3678
## 총장.및.전임교원수
## 1 650
## 2 418
## 3 440
## 4 358
## 5 624
## 6 390
test
객체를 사용하여 학교명을 key로 재적 학생 총합, 재학생 총합, 휴학생 총합, 총장 및 전임교원수를 value로 하여 gather()
를 적용,test_gat
객체에 할당하시오## 학교명 본분교 학생구분 tot_num
## 1 가천대학교 본교 재적.학생.총합 26411
## 2 경기대학교 본교 재적.학생.총합 17614
## 3 단국대학교 본교 재적.학생.총합 16946
## 4 수원대학교 본교 재적.학생.총합 14978
## 5 아주대학교 본교 재적.학생.총합 14141
## 6 한양대학교 분교1 재적.학생.총합 12910
test_gat
을 spread()
를 사용하여 원래 test
와 같은 모습으로 만들어 출력하시오.## 학교명 본분교 재적.학생.총합 재학생.총합 총장.및.전임교원수
## 1 가천대학교 본교 26411 19011 650
## 2 가톨릭대학교 본교 10174 7380 247
## 3 강남대학교 본교 10020 7279 222
## 4 경기대학교 본교 17614 12354 418
## 5 경동대학교 제4캠퍼스 877 620 32
## 6 단국대학교 본교 16946 11975 440
## 휴학생.총합
## 1 7400
## 2 2794
## 3 2741
## 4 5260
## 5 257
## 6 4971