简体   繁体   中英

Create a scatter plot of data which have the same unique ids but are unsorted in r

I have two data sets which have both the same unique ids, however, they are not sorted according to the unique ids.

Does someone knows how I could plot the data in respect to the unique ids?

Example of the first data set:

  Id Results
1 3e 10
2 2  15
3 1c 16

Example of the second data set:

  Id Results
1 1c 10
2 2  15
3 3e 16

You can use merge to create a single data set where the Ids are aligned and then plot them.

df1 = read.table(text="R Id Results
1 3e 10
2 2 15
3 1c 16",
header=TRUE, stringsAsFactors=FALSE)

df2 = read.table(text="R Id Results
1 1c 10
2 2 15
3 3e 16",
header=TRUE, stringsAsFactors=FALSE)

Merged = merge(df1[,2:3], df2[,2:3], by="Id")
plot(Merged[,2:3], pch=20)

If you really don't like the merged dataset solution, you can make an index that allows you to look up which Id in df2 matches the Id in df1.

df2_index = seq_along(df2)
names(df2_index) = df2$Id
plot(df1$Result, df2$Result[df2_index[df1$Id]], pch=20)

Or even simpler is

plot(df1$Result, df2$Result[match(df1$Id, df2$Id)], pch=20)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM