Gayathri Sripathy
Gayathri Sripathy

Reputation: 13

In R, how to assign the contents of a column to another if the row and column values match?

Sorry if my question was confusing. I am new to R. I have a dataset that has three columns - region, attack type (9 types) and count. gct is the name of this dataset. There are around 17,000 regions. Same region name is repeated for multiple rows if there is more than one attack type associated with it.

This is how the gct dataset looks like

I have another dataset (value1) which has the following columns - "region", "Bombing/Explosion","Armed Assault","Assassination","Hostage Taking","Facility/Infrastructure Attack","Unarmed Assault","Hostage Taking (Barricade Incident)","Hijacking","Unknown" (each and every attack type in gct has been changed to a column)

I would like to have the count of every attack type in gct dataset written under corresponding attack type column in the value1 dataset. The region column here has unique region names from gct database.

value1 dataset would look something like this

Any help is appreciated! Thanks in advance!

Upvotes: 1

Views: 47

Answers (1)

JMT2080AD
JMT2080AD

Reputation: 1079

I think you just need your first table. No need for the second. Your desired results can be obtained with reshape::cast. You will need to install reshape first.

try this:

library(reshape)

newGct <- cast(gct, City~AttackType, value = 'sr_count')

Depending on how your data is structured you may need to do this instead.

newGct <- cast(gct, City~AttackType, value = 'sr_count', fun.aggregate = sum)

Upvotes: 1

Related Questions