2

I am importing 2 columns of numeric data from a data file in the way defined in this answer:

data = Import["C:\\Users\\md\\Desktop\\myfile.txt", {"Data",  {All}, {1, 3}}];

These are my x and y values for a graph I'm plotting with ListPlot.

But I also need to apply some simple manipulations to the y values (the second column), like multiplying by 2 or taking the absolute value.

From the documentation I know it's possible by defining a function which takes a pair of values as arguments and then applying that function to data with Map, but that seems awfully troublesome when all I want is to multiply the y column by 2.

Is there a quick and simple way to do that?

This could either be done while importing, after importing, or while plotting, either way is fine.
I also don't care about which format I'm importing to, as long as it supports several thousand points.

Malabarba
  • 251
  • 1
  • 6

2 Answers2

3

Define some 2 dimensional data:

data = RandomInteger[{1, 2}, {10, 2}]

{{1, 1}, {2, 2}, {2, 2}, {2, 1}, {2, 1}, {2, 1}, {2, 1}, {2, 2}, {1, 2}, {1, 2}}

Tranpose

Transpose your 2D pairs of data so it is now too long lists, multiply the two lists by the factors you want ( here: 1 and 2 ) and then transpose the two long lists back again into 2D pairs of data.

Transpose@data {1, 2} // Transpose

{{1, 2}, {2, 4}, {2, 4}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 4}, {1, 4}, {1, 4}}

Map

You can achieve this in less characters with Map or short form /@ and a pure function like so:

{1,2} # & /@data

{{1, 2}, {2, 4}, {2, 4}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 4}, {1, 4}, {1, 4}}

The extent of the pure function is defined by the terminating & and its parameter(s) are accessed using # or #n for the nth parameter.

Here the # represents the pure function's first parameter which in this case is provided my Map and is a top level element of the list of data, a 2D point, {x,y}.

Mathematica automatically takes care of the list multiplication so that expressions of the following form are handled correctly:

{1, 2}  {a, b}

{a, 2 b}

image_doctor
  • 10,234
  • 23
  • 40
2

Since you're also asking how to take the absolute value of the data in the second column, I provide you this solution that uses Map:

data = RandomInteger[{-2, 2}, {10, 2}]

{{-1, 1}, {-1, 1}, {-1, 1}, {1, 1}, {-2, -2}, {1, 2}, {-1, 1}, {2, -1}, {-2, -2}, {0, -2}}

Map[{#[[1]], Abs[#[[2]]]} &, data]

{{-1, 1}, {-1, 1}, {-1, 1}, {1, 1}, {-2, 2}, {1, 2}, {-1, 1}, {2, 1}, {-2, 2}, {0, 2}}

Or with a shorter notation:

{#[[1]], Abs[#[[2]]]} & /@ data

{{-1, 1}, {-1, 1}, {-1, 1}, {1, 1}, {-2, 2}, {1, 2}, {-1, 1}, {2, 1}, {-2, 2}, {0, 2}}

VLC
  • 9,818
  • 1
  • 31
  • 60